<?// Определяем корневой путь
if(isset($_SERVER['HTTP_HOST'])){ // локалка/denwer
  if ($_SERVER['HTTP_HOST'] == 'neftemagnat.ru' && $_SERVER['SERVER_ADDR'] == '127.0.0.1')
    $DOCUMENT_ROOT = $_SERVER["DOCUMENT_ROOT"]; // Этот путь будет использоваться при работе с localhost
   elseif (($_SERVER['HTTP_HOST'] == 'neftemagnat.ru' || $_SERVER['HTTP_HOST'] == 'www.neftemagnat.ru') && $_SERVER['SERVER_ADDR'] != '127.0.0.1')
   	$DOCUMENT_ROOT = '/home/www/neftemagnat.ru/www';
  else $DOCUMENT_ROOT = '/home/neftemagnat.ru/www';
}
else
  $DOCUMENT_ROOT = ''; // Этот путь будет использоваться при работе отладчика Зенда (для корректной работы нужно внести правки в конфигурационный файл для ABSPATH)
$script = TRUE;
require_once($DOCUMENT_ROOT . '/../neftemagnat_start.php'); // Подключаем файл инициализации
// в файле инициализации обновляем время последнего посещения юзера, делаем доступным объект objUser
// и проверку на залогиненность $objUser->isLoggedIn() return true | false;
//--
setlocale(LC_ALL, 'ru_RU'); //установка русской локали

if ($objUser->isLoggedIn())
    $idUser= $objUser->getIdUser(); // изменить дописать 
else
    $idUser = NULL;
$path=""; //корень

$typeOfQuery = NULL;

if (isset($_POST["dataSend"])){ //проверяем было ли что-нибудь прислано от клиента через JS
    $dataFromClient = $_POST["dataSend"]; 
    $typeOfQuery = $dataFromClient["query"]; 
}

if (!$typeOfQuery){
    if (isset($_POST['editFirm'])) //если получены данные от формы AddAvatar, то значит мы ходим добавить аватар 
        $typeOfQuery = "addAvatar"; 
}

if (!$typeOfQuery){
    if (isset($_POST["upload_thumbnail"])){ //если получены данные от формы AddAvatar, то значит мы ходим добавить аватар 
        $typeOfQuery = "ThumbAvatar"; 
        $x1 = $_POST["x1"];
        $y1 = $_POST["y1"];
        $x2 = $_POST["x2"];
        $y2 = $_POST["y2"];
        $w = $_POST["w"];
        $h = $_POST["h"];
        $kod = $_POST["kod"];
    }
}



switch ($typeOfQuery) {

    case "regBuilding":

        /*
        * получение данных от клиента
        */
        $buildInfo = $dataFromClient['info'];

         /*
        * обезопасниваниввание данных, полученных от JS.
        */        
        //$name = iconv('UTF-8', 'windows-1251', $buildInfo['name']);
        $name = absolutelyEscapeString($buildInfo['name']);

       // $telephone = iconv('UTF-8', 'windows-1251', $buildInfo['telephone']);
        $telephone = absolutelyEscapeString($buildInfo['telephone']);

        //$site = iconv('UTF-8', 'windows-1251', $buildInfo['site']);
        $site = absolutelyEscapeString($buildInfo['site']);

        //$typeInn = iconv('UTF-8', 'windows-1251', $buildInfo['typeInn']);
        $typeInn = absolutelyEscapeString($buildInfo['typeInn']);

       // $class_ = iconv('UTF-8', 'windows-1251', $buildInfo['class_']);
        $class_ = absolutelyEscapeString($buildInfo['class_']);

       // $year = iconv('UTF-8', 'windows-1251', $buildInfo['year']);
        $year = absolutelyEscapeString($buildInfo['year']);

       // $numberFloors = iconv('UTF-8', 'windows-1251', $buildInfo['numberFloors']);
        $numberFloors = absolutelyEscapeString($buildInfo['numberFloors']);

       // $lat = iconv('UTF-8', 'windows-1251', $buildInfo['lat']);
        $lat = absolutelyEscapeString($buildInfo['lat']);

        //$lng = iconv('UTF-8', 'windows-1251', $buildInfo['lng']);
        $lng = absolutelyEscapeString($buildInfo['lng']);

        //$latExact = iconv('UTF-8', 'windows-1251', $buildInfo['latExact']);
        $latExact = absolutelyEscapeString($buildInfo['latExact']);

        //$lngExact = iconv('UTF-8', 'windows-1251', $buildInfo['lngExact']);
        $lngExact = absolutelyEscapeString($buildInfo['lngExact']);

        //$addressFull = iconv('UTF-8', 'windows-1251', $buildInfo['addressFull']);
        $addressFull = absolutelyEscapeString($buildInfo['addressFull']);

        //$city = iconv('UTF-8', 'windows-1251', $buildInfo['city']);
        $city = absolutelyEscapeString($buildInfo['city']);

       // $square = iconv('UTF-8', 'windows-1251', $buildInfo['square']);
        $square = absolutelyEscapeString($buildInfo['square']);

        //$address = iconv('UTF-8', 'windows-1251', $buildInfo['address']);
        $address = absolutelyEscapeString($buildInfo['address']);

        //$numStuff = iconv('UTF-8', 'windows-1251', $buildInfo['numStuff']);
        $numStuff = absolutelyEscapeString($buildInfo['numStuff']);

        /*
        * Дальше идет блок, который проверят корректность введенных данных
        */
        $error = NULL;

        //$name
        if ($name == '' && !$error)
            $error = 'Вы не ввели название фирмы';

        if (strlen($name) < 10 && !$error)
            $error = 'Слишком короткое название фирмы';

        if (strlen($name) > 500 && !$error)
            $error = 'Слишком длинное название фирмы';


        //$telephone
        if ($telephone == '' && !$error)
            $error = 'Вы не ввели телефон';

        if (strlen($telephone) < 3 && !$error)
            $error = 'Слишком короткий номер телефона';

        if (strlen($telephone) > 15 && !$error)
            $error = 'Слишком длинное номер телефона';


        //$site
        if (empty($site) && !$error)
            $error = 'Вы не ввели сайт';

        if (strlen($site) < 3 && !$error)
            $error = 'Слишком короткий адрес сайта';

        if (strlen($site) > 35 && !$error)
            $error = 'Слишком длинный адрес сайта';


        //$typeInn   
        if (($typeInn == '' || $typeInn == '0') && !$error)
            $error = 'Вы не выбрали тип здания';

        if (!filter_var($typeInn, FILTER_VALIDATE_INT) && !$error)
            $error = "Неизвестная ошибка_log.1 (что-то с типом здания)";

        if (!$error && ( $typeInn < 0 || $typeInn > 7))
            $error = "Неизвестная ошибка_log.2 (что-то с типом здания)";


        //$class
        if (($class_ == '' || $class_ == '0') && !$error)
            $error = 'Вы не выбрали класс здания';

        if (!filter_var($class_, FILTER_VALIDATE_INT) && !$error)
            $error = "Неизвестная ошибка_log.3 (что-то с классом здания)";

        if (!$error && ( $class_ < 0 || $class_ > 7))
            $error = "Неизвестная ошибка_log.4 (что-то с классом здания)";

        //$year
        if (($year == '' || $year == '0') && !$error)
            $error = 'Вы не выбрали год постойки здания';

        if (!filter_var($year, FILTER_VALIDATE_INT) && !$error)
            $error = "Неизвестная ошибка_log.5 (что-то с годом здания)";

        if (!$error && ( $year < 1800 || $year > 2012))
            $error = "Неизвестная ошибка_log.6 (что-то с годом здания)";

        //$numberFloors
        if (($numberFloors == '' || $numberFloors == '0') && !$error)
            $error = 'Вы не указали количество этажей в здании';

        if (!filter_var($numberFloors, FILTER_VALIDATE_INT) && !$error)
            $error = "Неизвестная ошибка_log.7 (что-то с количество этажей не так)";

        if (!$error && $numberFloors < 0 )
            $error = "Количество этажей не может быть отрицательным";

        if (!$error && $numberFloors > 100)
            $error = "Слишком большое количество этажей";

        //$square
        if (($square == '' || $square == '0') && !$error)
            $error = 'Вы не указали площадь здания';

        if (!filter_var($square, FILTER_VALIDATE_INT) && !$error)
            $error = "Неизвестная ошибка_log.8 (что-то с площадью здания)";

        if (!$error && $square < 0 )
            $error = "Площадь здания не может быть отрицательной";

        if (!$error && $square > 10000000)
            $error = "Слишком большая площадь здания";

        //$idUser
        if (!$idUser && !$error)
            $error = "Неизвестная ошибка_log.9 (что-то с регистрацией пользователя)";


        //$lat
        if ($lat != '' && $lat != '0' && !$error)
            if (!filter_var($lat, FILTER_VALIDATE_FLOAT))
                $error = "Неизвестная ошибка_log.20 (что-то с неточной широтой)";

        //$lng
        if ($lng != '' && $lng != '0' && !$error)
            if (!filter_var($lng, FILTER_VALIDATE_FLOAT))
                $error = "Неизвестная ошибка_log.21 (что-то с неточной долготой)";   


        //$latExact
        if ($latExact != '' && $latExact != '0' && !$error)
            if (!filter_var($latExact, FILTER_VALIDATE_FLOAT))
                $error = "Неизвестная ошибка_log.22 (что-то с точной широтой)";

        //$lngExact
        if ($lngExact != '' && $lngExact != '0' && !$error)
            if (!filter_var($lngExact, FILTER_VALIDATE_FLOAT))
                $error = "Неизвестная ошибка_log.23 (что-то с точной долготой)";  

        if ((strlen($address) == 0 || $address == 'введите адрес') && !$error)
            $error = 'Не указан адрес';

        if (strlen($address) < 10 && !$error)
            $error = 'Адрес слишком короткий';

        if (strlen($address) > 300 && !$error)
            $error = 'Адрес слишком длинный';

        //$numStuff
        if (($numStuff == '' || $numStuff == '0') && !$error)
            $error = 'Вы не указали количество обслуживающего персонала';

        if (!filter_var($numStuff, FILTER_VALIDATE_INT) && !$error)
            $error = "Неизвестная ошибка_log.24 (что-то с полем ОБСЛУЖИВАЮЩИЙ ПЕРСОНАЛ)";

        if (!$error && $numStuff < 0 )
            $error = "Количество персонала не может быть отрицательным";

        if (!$error && $numStuff > 1000)
            $error = "Слишком большое количество обслуживающего персонала";

        //$city
        if (($city == '' || $city == '0') && !$error)
            $error = 'Вы не ввели или неправильно указали город';
        
        
        if (!$error) {
            $query = mysql_query("SELECT city_id
                FROM city
                WHERE name = '$city'");

            if (!mysql_fetch_array($query))
                $error = 'Не существует введенного города';          
        }

        //*******************************************************************
        //конец блока проверки корректности введенных данных
        //*******************************************************************

            $objJSON = new Service_JSON(); // иницилизация объета JSON

            if ($error) {
                // $error = iconv("cp1251", "utf-8", $error);
                $arrMess['status'] = 'false';
                $arrMess['error'] = $error;
                echo $objJSON->encode($arrMess);
            } else {

                /*
                * регистрация
                */
                $lat_ = $lat;
                $lng_ = $lng;

                if ($latExact != '' && $lngExact != ''){
                    $lat_ = $latExact;
                    $lng_ = $lngExact;
                }

                //получение айдишника города
                $query = mysql_query("SELECT city_id
                        FROM city
                        WHERE name = '$city'
                        AND country_id = 3159");

                $result = mysql_fetch_array($query);

                $idCity = $result['city_id'];

                //заносим данные в БД
                mysql_query("INSERT INTO building (id_building, name, type, address, id_city, phone, site, class, year_building, floors, square, lat, lng, id_user, date_reg, staff) 
                        VALUES ('', '$name', '$typeInn', '$address', '$idCity', '$telephone', '$site', '$class_', '$year', '$numberFloors', '$square', '$lat_', '$lng_', '$idUser', NOW(), '$numStuff')");

                //**********************************************************************
                // конец блока регистрации
                //**********************************************************************

                $query = mysql_query("SELECT MAX(id_building) AS mi
                    FROM building");
                $result = mysql_fetch_array($query);
                $idNewBuild = $result['mi'];

                $objSession->__set('idBuild', $idNewBuild);

                $arrMess['status'] = 'true';
                echo $objJSON->encode($arrMess);
            }
    break;
    
        case "getListOffices_offices":
            $nameBuilding = $dataFromClient['nameBuilding'];
            //$nameBuilding = iconv('UTF-8', 'windows-1251', $nameBuilding);
            $nameBuilding = absolutelyEscapeString($nameBuilding);
  
             $query = mysql_query("SELECT id_building 
                     FROM building 
                     WHERE name = '$nameBuilding'");
             
             if ($result = mysql_fetch_array($query)){
                $idBuilding = $result['id_building'];
            
            $query = mysql_query("SELECT id_office, number
                            FROM building_offices
                            WHERE id_building = '$idBuilding'
                            ORDER BY number ASC;");
            
                          echo '<span>';
                          
                          while ($result = mysql_fetch_array($query)){
                              echo $result['number'].', ';  
                          }
                          
                          echo '<span>';
             }
        break;             
       
     case "getCountFloors":
//             $idBuilding = $dataFromClient['idBuilding'];
//             $idBuilding = absolutelyEscapeString($idBuilding);
             
             $nameBuilding = $dataFromClient['nameBuilding'];
             $nameBuilding = absolutelyEscapeString($nameBuilding);
             //$nameBuilding = iconv('UTF-8', 'windows-1251', $nameBuilding);

             Service_Database::instance();
             
             $query = mysql_query("SELECT id_building 
                     FROM building 
                     WHERE name = '$nameBuilding'");
             
                          
             if ($result = mysql_fetch_array($query)){
                $idBuilding = $result['id_building'];
                $query = mysql_query("SELECT floors
                    FROM building
                    WHERE id_building = ".$idBuilding);

                if ($result = mysql_fetch_array($query)){
                    echo '<select id="numberFloor" onChange = "getOffices();" style="width: 233px; height: 24px;">';
                    echo '<option value="0"></option>';
                    $colFloors = (integer)$result['floors'];

                    for ($i = 1; $i<=$colFloors; $i++){
                        echo '<option value="'.$i.'">'.$i.'</option>';   
                    }
                    echo '</select>';
                }
                else
                    echo '';    
             }
      break;
             
      case "registrationOffice":
            
             /*
             * получение данных от клиента
             */
            $officeInfo = $dataFromClient['info'];
            
            
            /*
             * обезопасниваниввание данных, полученных от JS.
             */        
            //$name = iconv('UTF-8', 'windows-1251', $officeInfo['name']);
            $name = $officeInfo['name'];
            $name = absolutelyEscapeString($name);
            
           // $number = iconv('UTF-8', 'windows-1251', $officeInfo['number']);
            $number = $officeInfo['number'];
            $number = absolutelyEscapeString($number);
            $number = (integer) $number;
            
            //$floor = iconv('UTF-8', 'windows-1251', $officeInfo['floor']);
            $floor = $officeInfo['floor'];
            $floor = absolutelyEscapeString($floor);
            $floor = (integer) $floor;
            
            //$city = iconv('UTF-8', 'windows-1251', $officeInfo['city']);
            $city = $officeInfo['city'];
            $city = absolutelyEscapeString($city);
            
            //$square = iconv('UTF-8', 'windows-1251', $officeInfo['square']);
            $square = $officeInfo['square'];
            $square = absolutelyEscapeString($square);
            $square = (integer) $square;
            
            //$error = Firm_Firm::checkRegDataOffice($name, $number, $floor, $city, $square);
            /*
             * проверка данных на валидность
             */
             $error = NULL;

            //$name
            if ($name == '' && !$error)
                $error = 'Вы не ввели название корпуса';

            //$number
            if (($number == '' || $number == '0') && !$error)
                $error = 'Вы не указали номер кабинета';

            if (!filter_var($number, FILTER_VALIDATE_INT) && !$error)
                $error = "Некорректно введен номер кабиента(должно быть числовое значение)";

            if ($number < 0 && !$error)
                $error = "Номер кабинета не может быть отрицательным";

            //$floor
            if (($floor == '' || $floor == '0') && !$error)
                $error = 'Вы не указали номер этажа';

            if (!filter_var($floor, FILTER_VALIDATE_INT) && !$error)
                $error = "Неизвестная ошибка(что-то с номерром этажа)";

            if ($floor < 0 && !$error)
                $error = "Номер этажа не может быть отрицательным";

            //$city
            if (($city == '' || $city == '0') && !$error)
                $error = 'Вы не ввели или неправильно указали город';

            if (!$error) {
                $query = mysql_query("SELECT city_id
                    FROM city
                    WHERE name = '$city'");

                if (!mysql_fetch_array($query))
                    $error = 'Не существует введенного города';          
            }

            //проверка существования такаго здания с таким этажом в БД     
            //получение айдишника города
            $query = mysql_query("SELECT city_id
                    FROM city
                    WHERE name = '$city'
                    AND country_id = 3159");

            $result = mysql_fetch_array($query);

            $idCity = $result['city_id'];

            $query = mysql_query("SELECT id_building, floors
                FROM building
                WHERE name = '$name'
                AND id_city = $idCity");

            if (!$result = mysql_fetch_array($query))
                $error = 'ошибка. что-то  с существованием такого здания';
            else {
                $floors = (integer)$result['floors'];
                $idBuilding = (integer)$result['id_building'];

                if ($floors < $floor)
                    $error = 'Такого этажа нет в этом здании';
            }


            if (!$error){
                $query = mysql_query("SELECT id_office
                    FROM building_offices
                    WHERE id_building = '$idBuilding'
                    AND number = '$number'");

                if (mysql_fetch_array($query))
                    $error = 'Такой оффис уже создан';
            }

            //$square
            if (($square == '' || $square == '0') && !$error)
                $error = 'Вы не указали площадь офиса';

            if (!filter_var($square, FILTER_VALIDATE_INT) && !$error)
                $error = "Неизвестная ошибка(что-то с площадью офиса)";

            if ($square < 0 && !$error)
                $error = "Площадь не может быть отрицательной";

            //********************************************************************
            //конец проверки данных на валидность
            //********************************************************************
            
            $objJSON = new Service_JSON(); // иницилизация
            
            if ($error){
                //$error = iconv("cp1251", "utf-8", $error);
                $arrMess['status'] = 'false';
                $arrMess['error'] = $error;
                echo $objJSON->encode($arrMess);
            }
            else{
                
                //Firm_Firm::regNewOffice($name, $number, $floor, $city, $square);
            /*
             * добавление нового офиса
             */    
                
            $query = mysql_query("SELECT city_id
                FROM city
                WHERE name = '$city'
                AND country_id = 3159");

            $result = mysql_fetch_array($query);

            $idCity = $result['city_id'];

            $query = mysql_query("SELECT id_building
                FROM building
                WHERE name = '$name'
                AND id_city = $idCity");

            $result = mysql_fetch_array($query);
            $idBuilding = (integer)$result['id_building'];

            //заносим данные в БД
            mysql_query("INSERT INTO building_offices (id_office, id_building, number, square, floor) VALUES ('', '$idBuilding', '$number', '$square', '$floor')");
                
                
            //********************************************************************
            //конец проверки данных на валидность
            //********************************************************************
                $arrMess['status'] = 'true';
                echo $objJSON->encode($arrMess);
            }           
        break;
        
        case "getTableOffices":
            $nameBuilding = $dataFromClient['nameBuilding'];
           // $nameBuilding = iconv('UTF-8', 'windows-1251', $nameBuilding);
            $nameBuilding = absolutelyEscapeString($nameBuilding);
            
            $numberFloor = $dataFromClient['numberFloor'];
            //$numberFloor = iconv('UTF-8', 'windows-1251', $numberFloor);
            $numberFloor = absolutelyEscapeString($numberFloor);
  
             $query = mysql_query("SELECT id_building 
                     FROM building 
                     WHERE name = '$nameBuilding'");
             if ($result = mysql_fetch_array($query)){
                $idBuilding = $result['id_building'];
            
            $query = mysql_query("SELECT *
                                    FROM building_offices
                                    LEFT JOIN firms
                                    USING ( id_office )
                                    WHERE building_offices.id_building = '$idBuilding'
                                    AND building_offices.floor = '$numberFloor'");
            
            $numberOffices = mysql_num_rows($query);
            
                //расчеты
                if ($numberOffices < 5)
                    $td = $numberOffices;
                else
                    $td = 5;
                
                $tr = ceil( $numberOffices/5 );
                   
            
            echo '<table border = "1">';
                for ($i = 0; $i < $tr; $i++) {
                    echo '<tr style="height: 90px">';
                        for ($j = 1; $j <= $td; $j++) {
                            if ( $result = mysql_fetch_array($query) ) {
                                $numberOffice = $result['number'];
                                $id_office = $result['id_office'];
                                
                                $x = '#7df9ff';
                                if ($result['name'])
                                    $x = '#fec8ca';
                                
                                echo '<td bgcolor = '.$x.' style="width: 90px;" onclick="editCell('.$id_office.')">';
                                
                                echo $numberOffice;
                            }
                            else
                                echo '<td style="width: 90px;">';
                            
                            echo '</td>';
                        }
                    echo '</tr>';
                }
            echo '</table>';
             }
        
        break;
        
        case "getInfOffice":
                               
             /*
             * получение данных от клиента
             */
            
            $numberCabinet = iconv('UTF-8', 'windows-1251', $dataFromClient['numberCabinet']);
            $numberCabinet = absolutelyEscapeString($numberCabinet);
            $id_office = (integer) $numberCabinet;
        
            $nameBuilding = $dataFromClient['nameBuilding'];
            //$nameBuilding = iconv('UTF-8', 'windows-1251', $nameBuilding);
            $nameBuilding = absolutelyEscapeString($nameBuilding);
            
            $numberFloor = $dataFromClient['numberFloor'];
            $numberFloor = iconv('UTF-8', 'windows-1251', $numberFloor);
            $numberFloor = absolutelyEscapeString($numberFloor);
            
             $query = mysql_query("SELECT id_building 
                     FROM building 
                     WHERE name = '$nameBuilding'");
             if ($result = mysql_fetch_array($query)){
                $idBuilding = $result['id_building'];         
                
       
            $query = mysql_query("SELECT *
                                    FROM building_offices
                                    LEFT JOIN firms
                                    USING ( id_office )
                                    WHERE building_offices.id_building = '$idBuilding'
                                    AND building_offices.floor = '$numberFloor'
                                    AND building_offices.id_office = '$id_office'");
                    
            $result = mysql_fetch_array($query);
            
            if ( $result['id_firm'] ) {
                $objJSON = new Service_JSON(); // иницилизаци
                $arrMess['status'] = 'false';
                echo $objJSON->encode($arrMess);
            } else {
                $text = '
                    <span></span>
                <div id="frameCell" style="position: absolute; display: none; width: 600px; background: #eef; padding: 1px 20px 30px 20px; margin: 20px;">
                <div id="closeCell" style="background: #fff; padding: 10px 0px 0px 20px; margin: 20px 0px 0px 500px;  width: 85px; height: 30px;" onClick="closeCell();">Закрыть</div>';
                $text .= 'ГОРОД : Санкт-Петербург<BR>';
                $text .= 'БЦ : ТестовыйТестовый<BR>';
                $text .= 'ЭТАЖ : 2<BR>';
                $text .= 'ОФИС СВОБОДЕН<BR>';
                $text .= 'ЗАНИМАБЩАЯ ФИРМА : ОАО супер-сила<BR>';
                $text .= 'Площадь офиса равна &nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp '.$result['square'].'<BR>';
                $text .= '<input type = "button" value = "Запомнить" onClick = "saveThisOffice('.$numberCabinet.')">';


                $text .= '';

    $text .= '</div>';


                $objJSON = new Service_JSON(); // иницилизация

            // $text = iconv("cp1251", "utf-8", $text);
                $arrMess['status'] = 'true';
                $arrMess['text'] = $text;
                echo $objJSON->encode($arrMess);
            }
            
        }
                  
        break;
        
        case "registrationFirm":
            
            /*
             * получение данных от клиента
             */
            $firmInfo = $dataFromClient['info'];
            
            
            /*
             * обезопасниваниввание данных, полученных от JS.
             */        
            $branch = iconv('UTF-8', 'windows-1251', $firmInfo['branch']);
            $branch = absolutelyEscapeString($branch);
            
            $mailbox = iconv('UTF-8', 'windows-1251', $firmInfo['mailbox']);
            $mailbox = absolutelyEscapeString($mailbox);
            
            $patternOfOwn = iconv('UTF-8', 'windows-1251', $firmInfo['patternOfOwn']);
            $patternOfOwn = absolutelyEscapeString($patternOfOwn);
            
            $dayReg = iconv('UTF-8', 'windows-1251', $firmInfo['dayReg']);
            $dayReg = absolutelyEscapeString($dayReg);
            
            $monthReg = iconv('UTF-8', 'windows-1251', $firmInfo['monthReg']);
            $monthReg = absolutelyEscapeString($monthReg);
            
            $yearReg = iconv('UTF-8', 'windows-1251', $firmInfo['yearReg']);
            $yearReg = absolutelyEscapeString($yearReg);
            
            $specialization = $firmInfo['specialization'];

            foreach ($specialization as $key => $value){
                $key = iconv('UTF-8', 'windows-1251', $key);
                $key = absolutelyEscapeString($key);
                
                $value = iconv('UTF-8', 'windows-1251', $value);
                $value = absolutelyEscapeString($value);
                
                $specialization[$key] = $value;
            }

            
            //$name = iconv('UTF-8', 'windows-1251', $firmInfo['name']);
            $name = $firmInfo['name'];
            $name = absolutelyEscapeString($name);
            
            $postRegistrant = iconv('UTF-8', 'windows-1251', $firmInfo['postRegistrant']);
            $postRegistrant = absolutelyEscapeString($postRegistrant);
            
            //$description = iconv('UTF-8', 'windows-1251', $firmInfo['description']);
            $description = $firmInfo['description'];
            $description = absolutelyEscapeString($description);
            
//            $sphere = iconv('UTF-8', 'windows-1251', $firmInfo['sphere']);
//            $sphere = absolutelyEscapeString($sphere);
              
            //$nameBuilding = iconv('UTF-8', 'windows-1251', $firmInfo['nameBuilding']);
            $nameBuilding = $firmInfo['nameBuilding'];
            $nameBuilding = absolutelyEscapeString($nameBuilding);
            
            $numberFloor = iconv('UTF-8', 'windows-1251', $firmInfo['numberFloor']);
            $numberFloor = absolutelyEscapeString($numberFloor);
            
            $office = iconv('UTF-8', 'windows-1251', $firmInfo['office']);
            $office = absolutelyEscapeString($office);
            
            //********************************************************************
            /*
             * проверка полученных данных на валидность
             */
            //********************************************************************
            $error = NULL;
        
        /*
         * ограничения
         */
        $minNameFirmLength = 1;
        $maxNameFirmLength = 20;
        
        $minDescriptionFirmLength = 1;
        $maxDescriptionFirmLength = 20;
        
        
        /*
         * проверка корректности
         */
        
        if (!$idUser && !$error && !filter_var($mailbox, FILTER_VALIDATE_EMAIL))
               $error = 'Почтовый ящик введен некорректно';

        if (!filter_var($patternOfOwn, FILTER_VALIDATE_INT) && !$error)
            $error = "Неизвестная ошибка_log.5";
        
        if (!$error && ($patternOfOwn < 1 || $patternOfOwn >13))
                $error = "Неизвестная ошибка_log.6";
        
        if (!filter_var($dayReg, FILTER_VALIDATE_INT) && !$error)
            $error = "Неизвестная ошибка_log.7";
        
        if (!filter_var($monthReg, FILTER_VALIDATE_INT) && !$error)
            $error = "Неизвестная ошибка_log.8";
        
        if (!filter_var($yearReg, FILTER_VALIDATE_INT) && !$error)
            $error = "Неизвестная ошибка_log.9";    
        
        $date = getdate();
        
        if ($date['year'] < $yearReg && !$error)
            $error = "Такая дата в будущем";
        
        if ($date['year'] == $yearReg && $date['mon'] < $monthReg && !$error)
            $error = "Такая дата в будущем";
        
        if ($date['year']==$yearReg && $date['mon'] == $monthReg && $date['mday'] < $dayReg && !$error)
            $error = "Такая дата в будущем";
        
        if (!checkdate($monthReg, $dayReg, $yearReg) && !$error)
            $error = "Такой даты не существует";
        

        if (!$error && strlen($name) < $minNameFirmLength)
            $error = "Название фирмы слишком короткое";
        
        if (!$error && strlen($name) > $maxNameFirmLength)
            $error = "Название фирмы слишком длинное";
        
        if (!filter_var($postRegistrant, FILTER_VALIDATE_INT) && !$error)
            $error = "Неизвестная ошибка_log.12";
        
        if (!$error && ($postRegistrant < 1 || $postRegistrant > 3))
                $error = "Неизвестная ошибка_log.13";
        
        if (!$error && strlen($description) < $minDescriptionFirmLength)
            $error = "Описание фирмы слишком короткое";
        
        if (!$error && strlen($description) > $maxDescriptionFirmLength)
            $error = "Описание фирмы слишком длинное";
              

        if (!filter_var($branch, FILTER_VALIDATE_INT) && !$error)
            $error = "Неизвестная ошибка_log.20";
        
        if (!$error && $branch != 0){
            $query = mysql_query("SELECT id_firm 
                FROM firms 
                WHERE id_firm = '$branch' 
                ;");
        
            if (!mysql_fetch_array($query)) $error = "Неизвестная ошибка_log.21";
        }
        
//        if (!$error){
//            $query = mysql_query("SELECT name 
//                FROM specialization 
//                WHERE id_sphere = '$sphere' 
//                AND id_specialization = '$specialization'");
//        
//            if (!mysql_fetch_array($query)) $error = "Неизвестная ошибка_log.16";
//        }
            //********************************************************************
            /*
             * конец проверк полученных данных на валидность
             */
            //********************************************************************
            
            
            
            $objJSON = new Service_JSON(); // иницилизация
            
            if ($error){
                $error = iconv("cp1251", "utf-8", $error);
                $arrMess['status'] = 'false';
                $arrMess['error'] = $error;
                echo $objJSON->encode($arrMess);
            }
            else{
          
            //********************************************************************
            /*
             * регистрация
             */
            //********************************************************************
/*
         * проверяем залогинен ли пользователь. Если да, то регим фирму не него. Если не залогинен, то у нас есть два варианта: почтовый ящик уже существует систему, тогда по нему вычисляем пользователя и опять же регистрируем фирму на него. Если почтового ящика нет в системе, то регим нового пользователя с таким почтовым ящиком и регистрируем фирму на него.
         * 
         */
        
        $query = mysql_query("SELECT id_building 
            FROM building 
            WHERE name = '$nameBuilding'");

        $result = mysql_fetch_array($query);
        $idBuilding = $result['id_building'];
        
        
        $idUserToReg = NULL; //переменная показывающая, на кого будет оформлять фирму в базе данных
        if ($idUser)
            $idUserToReg =  $idUser;//если юзер залогинен
        else{
            
            //проверяем, есть ли в системе такой почтовый ящик
            $query = mysql_query("SELECT id
                FROM temp1_users
                WHERE email = '$mailbox'");
            
            if ($result = mysql_fetch_array($query)){
                $idUserToReg = $result['id']; //если юзер не залогинен, но такой почтовый ящик уже есть в системе
            }       
            else{ //здесь регистрируем новго пользователя в  системе
                
                $arr = array('a','b','c','d','e','f','g','h','i','j','k','l','m','n','o','p','q','r','s',

't','u','v','x','y','z','A','B','C','D','E','F','G','H','I','J','K','L','M','N','O','P','R','S',

'T','U','V','X','Y','Z','1','2','3','4','5','6','7','8','9','0');

                // Генерируем пароль
                $pass = "";
                for($i = 0; $i < 17; $i++){
                    // Вычисляем случайный индекс массива
                    $index = rand(0, count($arr) - 1);
                    $pass .= $arr[$index];
                }          
                $passMD5 = md5($pass);
                
                $nick = $mailbox;
                

                mysql_query("INSERT INTO temp1_users (id, name, pass, fio, job, email, phone, url, icq, time, last_time, statususer) VALUES ('', '$nick', '$passMD5', '', '', '$mailbox', '', '', '', NOW(), NOW(), '')");
                
                //получаем айдишник нового пользователя в системе
                $query = mysql_query("SELECT MAX(id) AS mi 
                    FROM temp1_users");
                $result = mysql_fetch_array($query);
                
                $idUserToReg = $result['mi'];

            }
        }
        
        //теперь у нас есть и айдишник юзера на кого регистрировать фирму и даже пароль, если такого пользователя не было в системе
        echo "INSERT INTO firms (id_firm, name, description, telephone, branch, date_reg, id_office) VALUES ('', '$name', '$description', '', '$branch', NOW(), '$office')";
         mysql_query("INSERT INTO firms (id_firm, name, description, telephone, branch, date_reg, id_office) VALUES ('', '$name', '$description', '', '$branch', NOW(), '$office')");
         
         //получаем айдишник зарегенной фирмы
         $query = mysql_query("SELECT max(id_firm) as mi
             FROM firms");
         $result = mysql_fetch_array($query);
         
         $maxIdFirm = $result['mi'];
         
         //добавляем выбранные специализации для только что зарегенной фирмы
         foreach($specialization as $key => $value){
             if ($value != 0)   
                 mysql_query("INSERT INTO firm_specialization
                     (id_firm, id_specialization)
                     VALUES ('$maxIdFirm', '$value')"); 
         }
         
         //отправляем письмо пользователю 
         if (!isset($pass)){ 
                          
            //include BLOCKS.'template/mail/2.php';
            //Service_Mail::send($theme, $textMail, $fromWhom);
         }
         else{
              $arr = array('a','b','c','d','e','f','g','h','i','j','k','l','m','n','o','p','q','r','s',

't','u','v','x','y','z','A','B','C','D','E','F','G','H','I','J','K','L','M','N','O','P','R','S',

'T','U','V','X','Y','Z','1','2','3','4','5','6','7','8','9','0');

            // Генерируем инвайт
            $invite = "";
            for($i = 0; $i < 65; $i++){
                // Вычисляем случайный индекс массива
                $index = rand(0, count($arr) - 1);
                $invite .= $arr[$index];
            }          

            mysql_query("INSERT INTO invite (id_invite, kod, command, date_time, id_user) VALUES ('', '$invite', '1', NOW(), '$idUserToReg')"); 
            include BLOCKS.'template/mail/1.php';
            Service_Mail::send($theme, $textMail, $fromWhom);
         }
            //********************************************************************
            /*
             * конец регистрации
             */
            //********************************************************************
                
                $arrMess['status'] = 'true';
                echo $objJSON->encode($arrMess);
            }
            
            
//            echo $nameUser;
//            echo $familyUser;         
//            echo $latExact;
//            echo $lngExact;
//            echo $lat;
//            echo $lng;
//            echo $city;
//            echo $addressFull;
//            echo $mailbox;
//            echo $patternOfOwn;
//            echo $dayReg;
//            echo $monthReg;
//            echo $yearReg;
//            echo $specialization;
//            echo $name;
//            echo $postRegistrant;
//            echo $description;
//            echo $sphere;
         
        break;
        
        case "addVacancyFixedFirm":
        $vacancyInfo = $dataFromClient['vacancyInfo'];

        //$name = iconv('UTF-8', 'windows-1251', $vacancyInfo['name']);
        $name = $vacancyInfo['name'];    
        $name = absolutelyEscapeString($name);

        $currency = iconv('UTF-8', 'windows-1251', $vacancyInfo['currency']);
        $currency = absolutelyEscapeString($currency);

        $salaryFrom = iconv('UTF-8', 'windows-1251', $vacancyInfo['salaryFrom']);
        $salaryFrom = absolutelyEscapeString($salaryFrom);
        $salaryFrom = (integer) $salaryFrom;

        $salaryUnder = iconv('UTF-8', 'windows-1251', $vacancyInfo['salaryUnder']);
        $salaryUnder = absolutelyEscapeString($salaryUnder);
        $salaryUnder = (integer) $salaryUnder;

        $ageFrom = iconv('UTF-8', 'windows-1251', $vacancyInfo['ageFrom']);
        $ageFrom = absolutelyEscapeString($ageFrom);
        $ageFrom = (integer) $ageFrom;

        $ageUnder = iconv('UTF-8', 'windows-1251', $vacancyInfo['ageUnder']);
        $ageUnder = absolutelyEscapeString($ageUnder);
        $ageUnder = (integer) $ageUnder;

        $experienceFrom = iconv('UTF-8', 'windows-1251', $vacancyInfo['experienceFrom']);
        $experienceFrom = absolutelyEscapeString($experienceFrom);

        //$description = iconv('UTF-8', 'windows-1251//IGNORE', $vacancyInfo['description']);
        $description = $vacancyInfo['description'];
        $description = absolutelyEscapeStringFromWysiwyg($description);

        //$requirement = iconv('UTF-8', 'windows-1251//IGNORE', $vacancyInfo["requirement"]);
        $requirement = $vacancyInfo["requirement"];
        $requirement = absolutelyEscapeStringFromWysiwyg($requirement);

        //$conditions = iconv('UTF-8', 'windows-1251//IGNORE', $vacancyInfo['conditions']);
        $conditions = $vacancyInfo['conditions'];
        $conditions = absolutelyEscapeStringFromWysiwyg($conditions);

        $idContactUser = iconv('UTF-8', 'windows-1251', $vacancyInfo['idContactUser']);
        $idContactUser = absolutelyEscapeString($idContactUser);
        $idContactUser = (integer) $idContactUser;

        $contactInfo = iconv('UTF-8', 'windows-1251', $vacancyInfo['contactInfo']);
        $contactInfo = absolutelyEscapeString($contactInfo);

        $regime = iconv('UTF-8', 'windows-1251', $vacancyInfo['regime']);
        $regime = absolutelyEscapeString($regime);

        $type = iconv('UTF-8', 'windows-1251', $vacancyInfo['type']);
        $type = absolutelyEscapeString($type);

        $sex = iconv('UTF-8', 'windows-1251', $vacancyInfo['sex']);
        $sex = absolutelyEscapeString($sex);
        
        $idFirm = iconv('UTF-8', 'windows-1251', $vacancyInfo['idFirm']);
        $idFirm = absolutelyEscapeString($idFirm);
        $idFirm = (integer) $idFirm;

        //$error = Vacancy_Vacancy::validateRegData($cityName, $branch, $currency, $salaryFrom, $salaryUnder, $ageFrom, $ageUnder, $experienceFrom, $description, $requirement, $conditions, $idContactUser, $contactInfo, $name, $regime, $type, $sex, $idUser);
        //**************************************************************************************
        //проверка данных на корректность
        $error = NULL;
        
        $objJSON = new Service_JSON(); // иницилизация

        if (!$error){

        /*
     * разбиваем название вакансии на слова, находим для каждого слова код и заносим полученный код вакансии в БД
     */
    
//    $keywords = preg_split("/[\s,-]+/", $name);
//
//    $arrKey = array();
//    foreach ($keywords as $key => $value){
//        $query = mysql_query("SELECT id
//            FROM words_cods
//            WHERE word = '$value'");
//
//        if ($result = mysql_fetch_array($query)){
//            array_push($arrKey, $result['id']);      
//        } else {
//            mysql_query("INSERT INTO words_cods (id, word) VALUES ('', '$value')");
//            $codNewWord = mysql_insert_id();
//            array_push($arrKey, $codNewWord); 
//        }
//    }
//    
//    
//    if (isset($arrKey[0]))
//        $cod0 = $arrKey[0];
//    else
//        $cod0='';
//    
//    if (isset($arrKey[1]))
//        $cod1 = $arrKey[1];
//    else
//        $cod1='';
//        
//    if (isset($arrKey[2]))
//        $cod2 = $arrKey[2];
//    else
//        $cod2='';
//    
//    if (isset($arrKey[3]))
//        $cod3 = $arrKey[3];
//    else
//        $cod3='';  
//    
//    if (isset($arrKey[4]))
//        $cod4 = $arrKey[4];
//    else
//        $cod4='';
//    
//    if (isset($arrKey[5]))
//        $cod5 = $arrKey[5];
//    else
//        $cod5='';
    
    mysql_query ("INSERT INTO vacancy (id_vacancy, name, id_firm, sex, regime, type, salary_from, salary_under, currency, age_from, age_under, experienceFrom, description, requirement, `condition`, contact_person, contact) VALUES ('', '$name', '$idFirm',  '$sex', '$regime', '$type', '$salaryFrom', '$salaryUnder', '$currency', '$ageFrom', '$ageUnder', '$experienceFrom', '$description', '$requirement', '$conditions', '$idContactUser', '$contactInfo');");
//**************************************************************************************

        $arrMess['status'] = 'true';   

        } else {          
            $error = iconv("cp1251", "utf-8", $error);
            $arrMess['status'] = 'false';
            $arrMess['error'] = $error;
        }

        echo $objJSON->encode($arrMess); 
        
    break;
    
    case "getBCinfo":
       
        $city = $dataFromClient['city'];
        $city = absolutelyEscapeString($city);

        $buildings = $dataFromClient['buildings'];
        $buildings = absolutelyEscapeString($buildings);
        
        $typeInn = $dataFromClient['typeInn'];
        $typeInn = absolutelyEscapeString($typeInn);
        
        $address = $dataFromClient['address'];
        $address = absolutelyEscapeString($address);

//        echo $city;
//        echo $buildings;
//        echo $typeInn;
        
         //получение айдишника города
        $query = mysql_query("SELECT city_id
                FROM city
                WHERE name = '$city'
                AND country_id = 3159");

        if ($query) {
            $result = mysql_fetch_array($query);

            $idCity = $result['city_id'];
        
        }
        
        $query = mysql_query("SELECT * FROM building
            WHERE name = '$buildings'
            AND address = '$address'");
        
//        $result = mysql_fetch_array($query);
//        echo $result['name'];
        
        while ( $result = mysql_fetch_array($query) ) {
            ?>

                                
                                <BR>
                                <BR>

			<div class="cont_coloumn left">
				<div class="wth_dash">
					<span class="about_co" id="bName"><?echo $result['name'];?></span>
					<span> <? echo $result['address'];?></span><br />
					<span><b>Телефон:</b>&nbsp<? echo $result['phone'];?></span><br />
					<span><b>Сайт:</b> <a href="<? echo $result['site'];?>"><? echo $result['site'];?></a></span>
					<span class="vid_gr mt20">
                                            <?
                                            $query4 = mysql_query("SELECT count( id_building ) AS col
                                                FROM building
                                                LEFT JOIN building_offices
                                                USING ( id_building )
                                                LEFT JOIN firms
                                                USING ( id_office )
                                                WHERE NOT isnull( number )
                                                AND isnull( id_firm )
                                                AND id_building = '".$result['id_building']."'");
                                            $result4 = mysql_fetch_array($query4);
                                            echo $result4['col'];
                                            ?>
                                            
                                            
                                            свободных офисов</span>
				</div>
				<div class="wth_dash">	
					<span class="title_col">Описание здания</span>
					<p><b>Тип здания:</b> <?
                                        
                                        switch ( $result['type'] ) {
                                            
                                            case "0":
                                                echo "";
                                            break;
                                            
                                            case "1":
                                                echo "Бизнес центр";
                                            break;
                                        
                                            case "2":
                                                echo "Торгово-развлекательный центр";
                                            break;
                                        
                                            case "3":
                                                echo "Отдельно стоящее здание";
                                            break;
                                            
                                            case "4":
                                                echo "Государственное учреждение";
                                            break;
                                        
                                            case "5":
                                                echo "Жилое здание";
                                            break;
                                        
                                            case "6":
                                                echo "Завод";
                                            break;
                                        
                                            case "7":
                                                echo "Другое";
                                            break;
                                            
                                        }?></p>
					<p><b>Класс:&nbsp</b><?
                                        
                                        
                                            switch ( $result['class'] ) {
                                            case "0":
                                                echo "";
                                            break;
                                            
                                            case "1":
                                                echo "A";
                                            break;
                                        
                                            case "2":
                                                echo "A+";
                                            break;
                                        
                                            case "3":
                                                echo "A-";
                                            break;
                                            
                                            case "4":
                                                echo "B";
                                            break;
                                        
                                            case "5":
                                                echo "B+";
                                            break;
                                        
                                            case "6":
                                                echo "B-";
                                            break;
                                        
                                            case "7":
                                                echo "C";
                                            break;
                                        
                                            case "8":
                                                echo "C+";
                                            break;
                                        
                                            case "9":
                                                echo "C-";
                                            break;
                                        
                                            case "10":
                                                echo "D";
                                            break;
                                            
                                        }?> 
                                        </p>
					<p><b>Год постройки:</b>&nbsp<? echo $result['year_building'];?></p>
					<p><b>Этажность:</b>&nbsp<? echo $result['floors'];?></p>
					<p><b>Общая площадь:</b>&nbsp<? echo $result['square'];?></p>
				</div> 	
			</div> 
			<div class="cont_coloumn right">
				<div class="geo_map_off">
                                        <div id="map_canvas" style="margin: 20px auto; padding: 20px">
                                        </div>
                                </div>
                            
                            
                            
                            
                            
                            
                            
                            
                            
                            
                            
                            <span>
                                    <?$query1 = mysql_query("SELECT firms.name, firms.id_firm
                                        FROM firms
                                        LEFT JOIN building_offices
                                        USING ( id_office )
                                        LEFT JOIN building
                                        USING ( id_building )
                                        WHERE id_building = (SELECT id_building
                                        FROM building
                                        WHERE name = '$buildings')
                                        LIMIT 0, 3");
                                    ?> 
                                
                                    <p><b>Арендаторы:</b></p>   
                                    
                                    <?
                                    if ( $query1 ){
                                        while ( $result1 = mysql_fetch_array($query1) ){
                                           ?>
                                    <p><a href="#"><? echo $result1['name'];?></a><br /><span class="vid_gr">
                                            <?
                                            $query2 = mysql_query("SELECT count(vacancy.name) AS col
                                                FROM vacancy
                                                LEFT JOIN firms
                                                USING (id_firm)
                                                WHERE id_firm = '".$result1['id_firm']."'");
                                          
                                            $result2 = mysql_fetch_array($query2);
                                            echo $result2['col'];
                                            ?> вакансии</span></p><?
                                           
                                           }
                                    } else {
                                        
                                        echo 'Нет арендаторов';
                                    }
                                    ?>


                                </span>
                            
                            
                            
                            
                            
                            
                            
                            
                            
                            
                            
                            
                            
                        </div>
			<div class="clear"></div> 
			<div class="plan">
				<ul class="plan_u">
					<li><b>Планировка:</b></li>
                                        <? for ($i = 1; $i <= $result['floors']; $i++){ ?>
					<li><a href="#" onClick="showPlan(<?echo $i;?>); return false;"><? echo $i; ?> этаж</a></li> <?}?>
				</ul>
				<div class="plan_map"><div id="showPlan" style="float: left;"></div></div>
                                <BR>
			</div>
                        

                        
		</div> 
    <input type="hidden" id="lat" value="<?echo $result['lat']?>">
    <input type="hidden" id="lng" value="<?echo $result['lng']?>">
    
 <?
            
            
        }
        
        
    break;
    
    case "showPlan":
        
         $city = $dataFromClient['city'];
        $city = absolutelyEscapeString($city);

        $buildings = $dataFromClient['buildings'];
        $buildings = absolutelyEscapeString($buildings);
        
        $typeInn = $dataFromClient['typeInn'];
        $typeInn = absolutelyEscapeString($typeInn);
        
        $floor = $dataFromClient['floor'];
        $floor = absolutelyEscapeString($floor);  
    break;

    case "searchVacancy":
        $vacancyInfo = $dataFromClient['vacancyInfo'];

        $salaryFrom = iconv('UTF-8', 'windows-1251', $vacancyInfo['salaryFrom']);
        $salaryFrom = absolutelyEscapeString($salaryFrom);
        $salaryFrom = (integer) $salaryFrom;

        $salaryUnder = iconv('UTF-8', 'windows-1251', $vacancyInfo['salaryUnder']);
        $salaryUnder = absolutelyEscapeString($salaryUnder);
        $salaryUnder = (integer) $salaryUnder;

        $ageFrom = iconv('UTF-8', 'windows-1251', $vacancyInfo['ageFrom']);
        $ageFrom = absolutelyEscapeString($ageFrom);
        $ageFrom = (integer) $ageFrom;

        $ageUnder = iconv('UTF-8', 'windows-1251', $vacancyInfo['ageUnder']);
        $ageUnder = absolutelyEscapeString($ageUnder);
        $ageUnder = (integer) $ageUnder;

        $experienceFrom = iconv('UTF-8', 'windows-1251', $vacancyInfo['experienceFrom']);
        $experienceFrom = absolutelyEscapeString($experienceFrom);
        $experienceFrom = (integer)$experienceFrom;

        $regime = iconv('UTF-8', 'windows-1251', $vacancyInfo['regime']);
        $regime = absolutelyEscapeString($regime);
        $regime = (integer)$regime;
        
        $type = iconv('UTF-8', 'windows-1251', $vacancyInfo['type']);
        $type = absolutelyEscapeString($type);
        $type = (integer)$type;

        $sex = iconv('UTF-8', 'windows-1251', $vacancyInfo['sex']);
        $sex = absolutelyEscapeString($sex);
        $sex = (integer)$sex;
        
        
        /*
         * формируем запрос к БД
         */
        
        $query = "SELECT id_vacancy, name, id_firm
            FROM vacancy
            WHERE 1=1
            AND salary_from <= '$salaryUnder'
            AND salary_under >= '$salaryFrom'
            AND age_from <= '$ageUnder'
            AND age_under >= '$ageFrom'
            AND experienceFrom <= '$experienceFrom' ";
        
        if ($regime == '1')
            $query .= "AND regime = 1";
        
        if ($regime == '2')
            $query .= "AND regime = 2";
                
        if ($regime == '3')
            $query .= "AND regime = 3";
       
        //*** 
        
        if ($type == '1')
            $query .= "AND type = 1";
        
        if ($type == '2')
            $query .= "AND type = 2";
                
        if ($type == '3')
            $query .= "AND type = 3";
        
        //*** 
        
        if ($sex == '1')
            $query .= "AND sex = 1";
        
        if ($sex == '2')
            $query .= "AND sex = 2";
                
        if ($sex == '3')
            $query .= "AND sex = 3";
        
        $query = mysql_query($query);
        
        ?><div style="float: left; width: 300px">
        <ul><?
        while ( $result = mysql_fetch_array($query) )
            echo '<li onMouseOver="showDetailVacancy('.$result['id_vacancy'].');"><span style="color: blue">'.$result['name'].'</span></li>';
        ?>
        </ul>
        </div>
        <div id="detailedInfo" style="float: right; width: 500px; margin: -200px 0px 0px 0px">
            
        </div>
        
        <?
    break;
    
    case "getDetailedVacancy":
        $idVacancy = $dataFromClient['idVacancy'];
        $idVacancy = absolutelyEscapeString($idVacancy);
        $idVacancy = (integer) $idVacancy;
        
        $query = mysql_query("SELECT vacancy.name AS nameVacancy, building.name AS nameBuilding, firms.name AS nameFirm, vacancy.salary_from AS salaryFrom, vacancy.salary_under AS salaryUnder, vacancy.age_from AS ageFrom, vacancy.age_under AS ageUnder, vacancy.experienceFrom AS experienceFrom, vacancy.description AS description, vacancy.requirement AS requirement, vacancy.condition AS condition1, vacancy.contact AS contact, vacancy.sex as sex, vacancy.regime as regime, vacancy.type as type 
                                FROM vacancy
                                LEFT JOIN firms
                                USING (id_firm)
                                LEFT JOIN building_offices
                                USING (id_office)
                                LEFT JOIN building
                                USING (id_building)
                                WHERE id_vacancy = '$idVacancy' ");
        $result = mysql_fetch_array($query);
        ?>
       <div id="frameMap" style="position: absolute; width: 500px; height: 400px; background: #fff; padding: 1px 20px 30px 20px; margin: -20px 20px 20px 20px;">
           <ul>
               <li>Название вакансии: <?=$result['nameVacancy']?></li>
               <li>Здание: <?=$result['nameBuilding']?></li>
               <li>Фирма: <?=$result['nameFirm']?></li>
               <li>Искомый пол: <?
               switch ( $result['sex'] ) {
                                            case "0":
                                                echo "не важно";
                                            break;
                                        
                                            case "1":
                                                echo "Мужской";
                                            break;
                                        
                                            case "2":
                                                echo "Женский";
                                            break;
                }
               ?></li>
               <li>Режим работы:
               <? switch ( $result['regime'] ) {
                                            case "1":
                                                echo "Сменный график";
                                            break;
                                        
                                            case "2":
                                                echo "Полный день";
                                            break;
                                        
                                            case "3":
                                                echo "Свободный/гибкий график";
                                            break;
                }
                ?>
                </li>
               <li>Тип работы: 
                <? switch ( $result['type'] ) {
                                            case "1":
                                                echo "Работа на территории работодателя";
                                            break;
                                        
                                            case "2":
                                                echo "На дому/удаленная работа";
                                            break;
                }
                ?>
    
                </li>
               <li>ЗП от: <?=$result['salaryFrom']?></li>
               <li>ЗП до: <?=$result['salaryUnder']?></li>
               <li>Возраст от: <?=$result['ageFrom']?></li>
               <li>Возраст до: <?=$result['ageUnder']?></li>
               <li>Опыт работы: от <?=$result['experienceFrom']?></li>
               <li>Описание: <?=$result['description']?></li>
               <li>Требования: <?=$result['requirement']?></li>
               <li>Условия: <?=$result['condition1']?></li>
               <li>Контактные данные: <?=$result['contact']?></li>
                                                            
           </ul>
           
           
           
           
           
<!--            <div id="closeMap" style="background: #fff; padding: 10px 0px 0px 20px; margin: 20px 0px 0px 500px;  width: 85px; height: 30px;" onClick="closeMap();">
                Закрыть
            </div>-->
     
 
        </div>	
        

     <?   
    break;

      case "getListBC":
        $city = $dataFromClient['city'];
        $city = absolutelyEscapeString($city);
        
        $typeInn = $dataFromClient['typeInn'];
        $typeInn = absolutelyEscapeString($typeInn);
        
        $list1 = 1;
        $list2 = 1;
        
        $beginList = ($list1-1)*100 + ($list2-1)*10;
        $endList = ($list1-1)*100 + ($list2)*10 - 1;
        
        $query = mysql_query("SELECT *, building.name AS buildName, building.address AS buildAddress
                            FROM building  
                            LEFT JOIN city
                            ON (city_id = id_city)
                            WHERE city.name = '$city'
                            AND building.type = '$typeInn'
                            ");
        
        $numberBuildings = mysql_num_rows($query);
        
        $query = mysql_query("SELECT *, building.name AS buildName, building.address AS buildAddress
            FROM building  
            LEFT JOIN city
            ON (city_id = id_city)
            WHERE city.name = '$city'
            AND building.type = '$typeInn'
            LIMIT $beginList, $endList
        ");
        
            $i=0;
        while ($query && ($result = mysql_fetch_array($query)) && ($i <10) ) {
            $i++;
            
        ?>    
                        <div class="bt_dash">
                        <table class="ab_off">
                                <tr>
                                        <td>
                                                <span class="about_co"><?=$result['buildName']?>&nbsp(<?=$result['buildAddress']?>)</span><br />
                                                <a href="#"><img src="images/temp/off.jpg" alt="" /></a>
                                        </td>
                                        <td>
                                                <p><span class="sp_grey pr10"><b>Класс:</b></span>
                                                 <?
                                            switch ( $result['class'] ) {
                                                case "0":
                                                    echo "";
                                                break;

                                                case "1":
                                                    echo "A";
                                                break;

                                                case "2":
                                                    echo "A+";
                                                break;

                                                case "3":
                                                    echo "A-";
                                                break;

                                                case "4":
                                                    echo "B";
                                                break;

                                                case "5":
                                                    echo "B+";
                                                break;

                                                case "6":
                                                    echo "B-";
                                                break;

                                                case "7":
                                                    echo "C";
                                                break;

                                                case "8":
                                                    echo "C+";
                                                break;

                                                case "9":
                                                    echo "C-";
                                                break;

                                                case "10":
                                                    echo "D";
                                                break;
                                            }
                                            ?></p>
                                                <p><span class="sp_grey pr10"><b>Общ.площадь</b></span><?=$result['square']?> кв.м.</p>
                                                <ul class="more_map">
                                                        <li><a href="<?=W_ABSPATH?>bc/<?=$result['id_building']?>" class="more_icon">Подробнее</a></li>
                                                        <li><a href="#" class="map_icon" onClick="pokazat_kartu('<? echo $result['id_building']?>', '<?=$result['lat']?>', '<?=$result['lng']?>', '<?=$result['name']?>'); return false;">На карте</a></li>
                                                </ul>
                                        </td>
                                        <td>
                                                <a href="#" class="free_off_sp"><?
                                                
                                                $query4 = mysql_query("SELECT count( id_building ) AS col
                                                FROM building
                                                LEFT JOIN building_offices
                                                USING ( id_building )
                                                LEFT JOIN firms
                                                USING ( id_office )
                                                WHERE NOT isnull( number )
                                                AND isnull( id_firm )
                                                AND id_building = '".$result['id_building']."'");
                                            $result4 = mysql_fetch_array($query4);
                                            echo $result4['col'];
                                                ?> свободных офисов</a>
                                        </td>
                                </tr>
                        </table>
                </div><!-- .bt_dash -->
                
                <div id="frameMap_<?=$result['id_building']?>" style="display: none; width: 600px; height: 600px; padding: 1px 20px 30px 20px; margin: 20px;">
                    <div class="closeMap" id="closeMap" style="background: #fff; padding: 10px 0px 0px 20px; margin: 20px 0px 0px 500px;  width: 85px; height: 30px;" onClick="closeMap(<?=$result['id_building']?>);">
                        Закрыть
                    </div>

                    <div class="map_canvas" id="map_canvas_<?=$result['id_building']?>" style="margin: 20px auto; padding: 20px">
                    </div>
                </div>	
                

            
         <?   
        }
         $x100 = ceil( $numberBuildings/100 );
        
        if ($list1 == $x100)
            $x10 = ceil (( $numberBuildings - $x100*100 + 100 ) / 10);
        if ($list1 > $x100)
            $x10 = 0;
        if ($list1 < $x100)
            $x10 = 10;
               
        ?>
                        <div class="bt_dash">
                                      <span style="text-align: center;">X30<span>
				<ul class="biz_pagng">
                                    <? for ($i=1; $i <= $x100;  $i++)
                                        if ($i == $list1)
                                            echo '<li><a style="color: red" href="'.W_ABSPATH.'searchbc/'.$i.'/1/'.$city.'/'.$typeInn.'">'.$i.'00</a></li>';  
                                        else
                                            echo '<li><a href="'.W_ABSPATH.'searchbc/'.$i.'/1/'.$city.'/'.$typeInn.'">'.$i.'00</a></li>';  
                                    ?>
				</ul>
			</div><!-- .bt_dash -->
                        <div class="bt_dash">
				<ul class="biz_pagng">
                                    <? for ($i=1; $i <= $x10; $i++)
                                            if ($i == $list2)
                                                echo '<li><a style="color: red" href="'.W_ABSPATH.'searchbc/'.$list1.'/'.$i.'/'.$city.'/'.$typeInn.'"/>'.$i.'0</a></li>';
                                            else
                                                echo '<li><a href="'.W_ABSPATH.'searchbc/'.$list1.'/'.$i.'/'.$city.'/'.$typeInn.'"/>'.$i.'0</a></li>';
                                    ?>
				</ul>
			</div><!-- .bt_dash -->  

            <?
          
          
          
          
          
          
          
      break;
  
  case "updateCoord":
//      $id = $dataFromClient['id'];  
//      
//      $query = mysql_query("SELECT address, lat, lng 
//        FROM building
//        WHERE id_building = '$id'
//        ");
//    
//    $result = mysql_fetch_array($query);
//        
//        $address = $result['address'];
//        
//        $lat = $result['lat'];
//        
//        $lng = $result['lng'];
//        
//    $objJSON = new Service_JSON(); // иницилизация объета JSON
//
//                $arrMess['status'] = 'true';
//                $arrMess['address'] = $address;
//                echo $objJSON->encode($arrMess);
//    
    
  break;
      
   case "insertCoord":
//       $id = $dataFromClient['id']; 
//       
//        $lat = $dataFromClient['lat'];   
//        $lat = round ( $lat , 7);
//        
//        $lng = $dataFromClient['lng'];      
//        $lng = round ( $lng , 7);
//       
//       mysql_query("INSERT INTO building_ (id, lat, lng) VALUES ('$id', '$lat', '$lng')");
       
   break;

    case "getListFirm":
        
        $way = 1.5; //расстояние, в радиусе которого ищутся фирмы        
        
        $city = $dataFromClient['city'];
        $city = absolutelyEscapeString($city);
        
        $vacancyFree = $dataFromClient['vacancyFree'];
        $vacancyFree = absolutelyEscapeString($vacancyFree);
        
        $specialization = $dataFromClient['specialization'];
        
        $lat0rad = pi()*(absolutelyEscapeString($dataFromClient['lat']))/180;
        $lng0rad = pi()*(absolutelyEscapeString($dataFromClient['lng']))/180;

        $spec = '';
        
            foreach ($specialization as $key => $value){
                $key = iconv('UTF-8', 'windows-1251', $key);
                $key = absolutelyEscapeString($key);
                
                $value = iconv('UTF-8', 'windows-1251', $value);
                $value = absolutelyEscapeString($value);
                
                $specialization[$key] = $value;
                
                $spec .= $value.', ';
            }
        
            $spec = substr($spec, 0, strlen($spec)-2);
                    
                    
  if ($vacancyFree == 1)                   
          $query = mysql_query("SELECT DISTINCT firms.id_firm AS id_firm, firms.telephone AS telephone, firms.description AS description, firms.name AS name, building.lat, building.lng FROM firms
                  LEFT JOIN building_offices USING (id_office)
                  LEFT JOIN building USING (id_building)
LEFT JOIN firm_specialization
USING (id_firm)
WHERE firm_specialization.id_specialization IN ($spec)
AND firms.id_firm IN (SELECT id_firm FROM firms WHERE id_office IN (SELECT id_office FROM building_offices WHERE id_building IN (SELECT id_building FROM building WHERE id_city = (SELECT city_id FROM city WHERE name = '$city')) ) ) AND (SELECT count(id_vacancy) FROM vacancy WHERE id_firm = firms.id_firm) >= 0");
  else
      $query = mysql_query("SELECT DISTINCT firms.id_firm AS id_firm, firms.telephone AS telephone, firms.description AS description, firms.name AS name, building.lat AS lat, building.lng AS lng FROM firms
    LEFT JOIN building_offices USING (id_office)
    LEFT JOIN building USING (id_building)
LEFT JOIN firm_specialization
USING (id_firm)
WHERE firm_specialization.id_specialization IN ($spec)
AND firms.id_firm IN (SELECT id_firm FROM firms WHERE id_office IN (SELECT id_office FROM building_offices WHERE id_building IN (SELECT id_building FROM building WHERE id_city = (SELECT city_id FROM city WHERE name = '$city')) ) ) AND (SELECT count(id_vacancy) FROM vacancy WHERE id_firm = firms.id_firm) > 0");
          
          
        ob_start();
            echo '<BR>';
            echo '<BR>';
            include BLOCKS.'getListFirms.php';
            $answer['text2']  .= ob_get_contents();
        
        ob_end_clean();
        
        
        if ($vacancyFree == 1)                   
                $query = mysql_query("SELECT DISTINCT firms.name, building.lat, building.lng FROM firms
LEFT JOIN building_offices USING (id_office)
LEFT JOIN building USING (id_building)
        LEFT JOIN firm_specialization
        USING (id_firm)
        WHERE firm_specialization.id_specialization IN ($spec)
        AND firms.id_firm IN (SELECT id_firm FROM firms WHERE id_office IN (SELECT id_office FROM building_offices WHERE id_building IN (SELECT id_building FROM building WHERE id_city = (SELECT city_id FROM city WHERE name = '$city')) ) ) AND (SELECT count(id_vacancy) FROM vacancy WHERE id_firm = firms.id_firm) >= 0");
        else
            $query = mysql_query("SELECT DISTINCT firms.name, building.lat, building.lng FROM firms
LEFT JOIN building_offices USING (id_office)
LEFT JOIN building USING (id_building)
        LEFT JOIN firm_specialization
        USING (id_firm)
        WHERE firm_specialization.id_specialization IN ($spec)
        AND firms.id_firm IN (SELECT id_firm FROM firms WHERE id_office IN (SELECT id_office FROM building_offices WHERE id_building IN (SELECT id_building FROM building WHERE id_city = (SELECT city_id FROM city WHERE name = '$city')) ) ) AND (SELECT count(id_vacancy) FROM vacancy WHERE id_firm = firms.id_firm) > 0");


       
            $i = 0;
            $str = '';

            while ($result = mysql_fetch_array($query)){
                $obj['name'] = $result['name'];
                $obj['lat'] = $result['lat'];
                $obj['lng'] = $result['lng'];
                $obj['id'] = $i;
                
                
                
                
                 //проверка на расстояние
                    $lat1rad = pi()*($result['lat'])/180;
                    $lng1rad = pi()*($result['lng'])/180;
                    
                    $k = 117; //коэффициент
                    
                    if ( $lat0rad != 0 && $lng0rad != 0 )
                        $distance = (180/pi())*$k*sqrt(($lat1rad-$lat0rad)*($lat1rad-$lat0rad) + cos($lng0rad)*cos($lng0rad)*(($lat1rad-$lat0rad)*($lat1rad-$lat0rad)));
                    else
                        $distance = 0;
                    
                //echo $distance;
                if ($distance < $way) {
                    $str[$i] = $obj;
                    $i++;
                }
            }
       
       $answer['coord'] = $str;
            
        
        
        //****************************************
        
        
        
        
        
        
        
        
        $cityTranslit = translitIt($city);
        
        $query = mysql_query("SELECT latitude AS lat, longitude AS lng
                FROM geoip_city 
                WHERE city = '$cityTranslit'");
        
        $lat = NULL;
        $lng = NULL;
       
        if ( $result = mysql_fetch_array($query) ) {
            
            $lat = $result['lat'];
            $lng = $result['lng'];
            
        }
        
        $answer['lat'] = $lat;
        $answer['lng'] = $lng;
            

        $objJSON = new Service_JSON(); // иницилизация объета JSON
        echo $objJSON->encode($answer);  
              
            
    break;
    
    case "getBuildTypes":
        
        $city = $dataFromClient['city'];
        $city = absolutelyEscapeString($city);
        
        $page = $dataFromClient['page'];
        $page = absolutelyEscapeString($page);
        
        $query = mysql_query("SELECT type, count(id_building) AS x
                                FROM building
                                WHERE id_city
                                IN (
                                    SELECT city_id
                                    FROM city
                                    WHERE name = '$city'
                                    )
                                GROUP BY type ORDER BY type ASC;");
        $answer['text1'] = '
          
            <span>Тип здания : &nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp</span>
            <select id="typeInn" style="width: 233px; height: 24px;" onChange="getBCbyType(1);">
        ';
        
        $sum = 0;
                
        while ( $result = mysql_fetch_array($query) ) {
                     $sum = $sum + $result['x'];    
        }
        
        if ($sum)
            $answer['text1'] .= '<option value="0">Все Здания ('.$sum.')</option>';
        

        $query = mysql_query("SELECT type, count(id_building) AS x
                                FROM building
                                WHERE id_city
                                IN (
                                    SELECT city_id
                                    FROM city
                                    WHERE name = '$city'
                                    )
                                GROUP BY type ORDER BY type ASC;");
        
        while ( $result = mysql_fetch_array($query) ) {
            
            $type = $result['type'];
            
            if ($type == 1) 
                $answer['text1'] .= '<option value="1">Бизнес центр ('.$result['x'].')</option>';

            if ($type == 2) 
                $answer['text1'] .= '<option value="2">Торгово-развлекательный центр ('.$result['x'].')</option>';
            
            if ($type == 3) 
                $answer['text1'] .= '<option value="3">Отдельно стоящее здание ('.$result['x'].')</option>';
            
            if ($type == 4) 
                $answer['text1'] .= '<option value="4">Государственное учреждение ('.$result['x'].')</option>';
            
            if ($type == 5) 
                $answer['text1'] .= '<option value="5">Жилое здание ('.$result['x'].')</option>';
            
            if ($type == 6) 
                $answer['text1'] .= '<option value="6">Завод ('.$result['x'].')</option>';
            
            if ($type == 7) 
                $answer['text1'] .= '<option value="7">Другое... ('.$result['x'].')</option>';
            
        }
        
       
        
        $answer['text1'] .= '</select>';
        
        
        //получение координат города
          
        
        $cityTranslit = translitIt($city);
        
        $query = mysql_query("SELECT latitude AS lat, longitude AS lng
                FROM geoip_city 
                WHERE city = '$cityTranslit'");
        
        $lat = NULL;
        $lng = NULL;
       
        if ( $result = mysql_fetch_array($query) ) {
            
            $lat = $result['lat'];
            $lng = $result['lng'];
            
        }
        
        $answer['lat'] = $lat;
        $answer['lng'] = $lng;
        
        //-------------------------------------------
        
      
        
        $beginList = ($page-1)*10;
        
        $query = mysql_query("SELECT *, building.name AS buildName, building.address AS buildAddress
                            FROM building  
                            LEFT JOIN city
                            ON (city_id = id_city)
                            WHERE city.name = '$city'
                            ");
        
        $numberBuildings = mysql_num_rows($query);
        
        $pages = ceil ( $numberBuildings / 10);
        
        $query = mysql_query("SELECT *, building.id_building AS idBuilding, building.name AS buildName, building.address AS buildAddress
            FROM building  
            LEFT JOIN city
            ON (city_id = id_city)
            WHERE city.name = '$city'
            LIMIT $beginList, 10
        ");
        
        $answer['text2'] = '';

        
        //****
        //убогий костыль, но работает
        //***
        ob_start();

        $i=0;
        while ($query && ($result = mysql_fetch_array($query)) && ($i <10) ) {
            $i++;
            
            $idBuilding = $result['idBuilding'];
            include BLOCKS.'getBuildTypes.php'; 
       }
      
        $answer['text2']  = ob_get_contents();
        ob_end_clean();
        
        //**********
        
        ob_start();
        
            echo '<BR>';
            echo '<BR>';
            getPages('getBCtypes', $pages, $page, '' ,'', '', 6);
            $answer['text2']  .= ob_get_contents();
        
        ob_end_clean();

        
        $query = mysql_query("SELECT name, id_building, lat, lng FROM building WHERE id_city IN (
                                    SELECT city_id
                                    FROM city
                                    WHERE name = '$city'
                                    )");
            $i = 0;
            $str = '';

            while ($result = mysql_fetch_array($query)){
                $obj['name'] = $result['name'];
                $obj['lat'] = $result['lat'];
                $obj['lng'] = $result['lng'];
                $obj['id'] = $i;
                
                $str[$i] = $obj;
               
                $i++;
            }
            
            $answer['coord'] = $str;
        
             // getPages('', 2, 100, '' ,'','', 6);
    
        
        $objJSON = new Service_JSON(); // иницилизация объета JSON
        echo $objJSON->encode($answer);
    break;
    
    case "getBCbyType":
        
        $city = $dataFromClient['city'];
        $city = absolutelyEscapeString($city);
        
        $typeInn = $dataFromClient['typeInn'];
        $typeInn = absolutelyEscapeString($typeInn);
        
        $page = $dataFromClient['page'];
        $page = absolutelyEscapeString($page);
        
        
        //получение координат города
          
  
        
        $cityTranslit = translitIt($city);
        
        $query = mysql_query("SELECT latitude AS lat, longitude AS lng
                FROM geoip_city 
                WHERE city = '$cityTranslit'");
        
        $lat = NULL;
        $lng = NULL;
       
        if ( $result = mysql_fetch_array($query) ) {
            
            $lat = $result['lat'];
            $lng = $result['lng'];
            
        }
        
        $answer['lat'] = $lat;
        $answer['lng'] = $lng;
        
        //-------------------------------------------
        
      
        $beginList = ($page-1)*10;
        
        if ($typeInn == '0') {
            
            $query = mysql_query("SELECT *, building.name AS buildName, building.address AS buildAddress
                                FROM building  
                                LEFT JOIN city
                                ON (city_id = id_city)
                                WHERE city.name = '$city'
                                ");

            $numberBuildings = mysql_num_rows($query);

            $pages = ceil ($numberBuildings / 10);

            $query = mysql_query("SELECT *, building.id_building AS idBuilding, building.name AS buildName, building.address AS buildAddress
                FROM building  
                LEFT JOIN city
                ON (city_id = id_city)
                WHERE city.name = '$city'
                ORDER by buildName
                LIMIT $beginList, 10
            ");
            
            
        } else {
            $query = mysql_query("SELECT *, building.name AS buildName, building.address AS buildAddress
                                FROM building  
                                LEFT JOIN city
                                ON (city_id = id_city)
                                WHERE city.name = '$city'
                                AND building.type = '$typeInn'
                                ");

            $numberBuildings = mysql_num_rows($query);

            $pages = ceil ($numberBuildings / 10);

            $query = mysql_query("SELECT *, building.id_building AS idBuilding, building.name AS buildName, building.address AS buildAddress
                FROM building  
                LEFT JOIN city
                ON (city_id = id_city)
                WHERE city.name = '$city'
                AND building.type = '$typeInn'
                ORDER by buildName
                LIMIT $beginList, 10
            ");
         }
        
        $answer['text2'] = '';

        
        //****
        //убогий костыль, но работает
        //***
        ob_start();

        $i=0;
        while ($query && ($result = mysql_fetch_array($query)) && ($i <10) ) {
            
            $idBuilding = $result['idBuilding'];
            $i++;
            include BLOCKS.'getBuildTypes.php'; 
       }
      
        $answer['text2']  = ob_get_contents();
        ob_end_clean();
        
        //**********
        //листалка
        ob_start();
            echo '<BR>';
            echo '<BR>';
            getPages('getBCbyType', $pages, $page, '' ,'', '', 6);
            $answer['text2']  .= ob_get_contents();
        
        ob_end_clean();
        //-------------------------------------------
        
        if ($typeInn == 0){
            $query = mysql_query("SELECT name, id_building, lat, lng 
                FROM building 
                WHERE id_city IN (
                                    SELECT city_id
                                    FROM city
                                    WHERE name = '$city'
               )
               ");
            
        } else {
        $query = mysql_query("SELECT name, id_building, lat, lng 
                FROM building 
                WHERE id_city IN (
                                    SELECT city_id
                                    FROM city
                                    WHERE name = '$city'
               )
                AND type = '$typeInn'
                ");
        }
        
            $i = 0;
            $str = '';

            while ($result = mysql_fetch_array($query)){
                $obj['name'] = $result['name'];
                $obj['lat'] = $result['lat'];
                $obj['lng'] = $result['lng'];
                $obj['id'] = $i;
                
                $str[$i] = $obj;
               
                $i++;
            }
            
            $answer['coord'] = $str;
        
        
        $objJSON = new Service_JSON(); // иницилизация объета JSON
        echo $objJSON->encode($answer);
        
   break;
   
   case "getBCinDetail":
       
       $idBuilding = absolutelyEscapeString($dataFromClient['idBuilding']);
       
       $answer['text1'] = 0;
       
        ob_start();
            echo '<BR>';
            echo '<BR>';
            include BLOCKS.'getBCinDetail.php';
            $answer['text2']  .= ob_get_contents();
        
        ob_end_clean();

       
        $objJSON = new Service_JSON(); // иницилизация объета JSON
        echo $objJSON->encode($answer);
       
   break;



//******************************************************************************

    case "searchFirm":
        
        if ( isset ($dataFromClient['searchFirm'] ) )
            $searchFirm = absolutelyEscapeString($dataFromClient['searchFirm']);
        
        $city = $dataFromClient['city'];
        $city = absolutelyEscapeString($city);
        
        $vacancyFree = $dataFromClient['vacancyFree'];
        $vacancyFree = absolutelyEscapeString($vacancyFree);
         
        $specialization = $dataFromClient['specialization'];

        $spec = '';
        
            foreach ($specialization as $key => $value){
                $key = iconv('UTF-8', 'windows-1251', $key);
                $key = absolutelyEscapeString($key);
                
                $value = iconv('UTF-8', 'windows-1251', $value);
                $value = absolutelyEscapeString($value);
                
                $specialization[$key] = $value;
                
                $spec .= $value.', ';
            }
        
        $spec = substr($spec, 0, strlen($spec)-2);    
                    
  if ($vacancyFree == 1)                   
          $query = mysql_query("SELECT DISTINCT firms.id_firm, firms.telephone, firms.description, firms.name, building.lat AS lat, building.lng AS lng FROM firms
LEFT JOIN building_offices USING (id_office)
LEFT JOIN building USING (id_building)
LEFT JOIN firm_specialization
USING (id_firm)
WHERE firm_specialization.id_specialization IN ($spec)
AND firms.id_firm IN (SELECT id_firm FROM firms WHERE id_office IN (SELECT id_office FROM building_offices WHERE id_building IN (SELECT id_building FROM building WHERE id_city = (SELECT city_id FROM city WHERE name = '$city')) ) ) AND (SELECT count(id_vacancy) FROM vacancy WHERE id_firm = firms.id_firm) >= 0");
  else
      $query = mysql_query("SELECT DISTINCT firms.id_firm, firms.telephone, firms.description, firms.name, building.lat AS lat, building.lng AS lng FROM firms
LEFT JOIN building_offices USING (id_office)
LEFT JOIN building USING (id_building)
LEFT JOIN firm_specialization
USING (id_firm)
WHERE firm_specialization.id_specialization IN ($spec)
AND firms.id_firm IN (SELECT id_firm FROM firms WHERE id_office IN (SELECT id_office FROM building_offices WHERE id_building IN (SELECT id_building FROM building WHERE id_city = (SELECT city_id FROM city WHERE name = '$city')) ) ) AND (SELECT count(id_vacancy) FROM vacancy WHERE id_firm = firms.id_firm) > 0");
  

    
       
       //*************************************************   
          
  
       
       
       $answer['text1'] = 0;
       
        ob_start();
            echo '<BR>';
            echo '<BR>';
            include BLOCKS.'searchFirm.php';
            $answer['text2']  .= ob_get_contents();
        
        ob_end_clean();

          
        
        //***************** повторяем код, т.к. не знаю, как сбросить внутренний указатель в результате запроса sql
        //**********************************
        
        if ($vacancyFree == 1)                   
          $query = mysql_query("SELECT DISTINCT firms.id_firm, firms.telephone, firms.description, firms.name, building.lat AS lat, building.lng AS lng FROM firms
LEFT JOIN building_offices USING (id_office)
LEFT JOIN building USING (id_building)
LEFT JOIN firm_specialization
USING (id_firm)
WHERE firm_specialization.id_specialization IN ($spec)
AND firms.id_firm IN (SELECT id_firm FROM firms WHERE id_office IN (SELECT id_office FROM building_offices WHERE id_building IN (SELECT id_building FROM building WHERE id_city = (SELECT city_id FROM city WHERE name = '$city')) ) ) AND (SELECT count(id_vacancy) FROM vacancy WHERE id_firm = firms.id_firm) >= 0");
  else
      $query = mysql_query(" SELECT DISTINCT firms.id_firm, firms.telephone, firms.description, firms.name, building.lat AS lat, building.lng AS lng FROM firms
LEFT JOIN building_offices USING (id_office)
LEFT JOIN building USING (id_building)
LEFT JOIN firm_specialization
USING (id_firm)
WHERE firm_specialization.id_specialization IN ($spec)
AND firms.id_firm IN (SELECT id_firm FROM firms WHERE id_office IN (SELECT id_office FROM building_offices WHERE id_building IN (SELECT id_building FROM building WHERE id_city = (SELECT city_id FROM city WHERE name = '$city')) ) ) AND (SELECT count(id_vacancy) FROM vacancy WHERE id_firm = firms.id_firm) > 0");
  
  
       
            $i = 0;
            $str = '';

            while ($result = mysql_fetch_array($query)){
                
                if (  ($searchFirm == '') || ( false !== mb_strpos( mb_strtolower($result['name'], 'UTF-8'), mb_strtolower($searchFirm, 'UTF-8' ) ) ) ) {
                
                    
                    
                    
                    $obj['name'] = $result['name'];
                    $obj['lat'] = $result['lat'];
                    $obj['lng'] = $result['lng'];
                    $obj['id'] = $i;
            
                    $str[$i] = $obj;

                    $i++;
                
                }
            }
        
       $answer['coord'] = $str;
            
       
        //получение координат города
          
        

        
        $cityTranslit = translitIt($city);
        
        $query = mysql_query("SELECT latitude AS lat, longitude AS lng
                FROM geoip_city 
                WHERE city = '$cityTranslit'");
        
        $lat = NULL;
        $lng = NULL;
       
        if ( $result = mysql_fetch_array($query) ) {
            
            $lat = $result['lat'];
            $lng = $result['lng'];
            
        }
        
        $answer['lat'] = $lat;
        $answer['lng'] = $lng;
            

        $objJSON = new Service_JSON(); // иницилизация объета JSON
        echo $objJSON->encode($answer);      
    
          
         //************************************************* 
          
          
    break;
    
    case "searchHere":
        
        $way = 1.5; //расстояние, в радиусе которого ищутся фирмы        
        
        
        $vacancyFree = $dataFromClient['vacancyFree'];
        $vacancyFree = absolutelyEscapeString($vacancyFree);
        
        $specialization = $dataFromClient['specialization'];
        
        $lat = $dataFromClient['lat'];
        $lng = $dataFromClient['lng'];
        
        $lat0rad = pi()*(absolutelyEscapeString($dataFromClient['lat']))/180;
        $lng0rad = pi()*(absolutelyEscapeString($dataFromClient['lng']))/180;

        $spec = '';
        
            foreach ($specialization as $key => $value){
                $key = iconv('UTF-8', 'windows-1251', $key);
                $key = absolutelyEscapeString($key);
                
                $value = iconv('UTF-8', 'windows-1251', $value);
                $value = absolutelyEscapeString($value);
                
                $specialization[$key] = $value;
                
                $spec .= $value.', ';
            }
        
            $spec = substr($spec, 0, strlen($spec)-2);
                    
                    
  if ($vacancyFree == 1)                   
          $query = mysql_query("SELECT DISTINCT firms.id_firm AS id_firm, firms.telephone AS telephone, firms.description AS description, firms.name AS name, building.lat, building.lng FROM firms
                  LEFT JOIN building_offices USING (id_office)
                  LEFT JOIN building USING (id_building)
LEFT JOIN firm_specialization
USING (id_firm)
WHERE firm_specialization.id_specialization IN ($spec)
AND (SELECT count(id_vacancy) FROM vacancy WHERE id_firm = firms.id_firm) >= 0");
  else
      $query = mysql_query("SELECT DISTINCT firms.id_firm AS id_firm, firms.telephone AS telephone, firms.description AS description, firms.name AS name, building.lat, building.lng FROM firms
                  LEFT JOIN building_offices USING (id_office)
                  LEFT JOIN building USING (id_building)
LEFT JOIN firm_specialization
USING (id_firm)
WHERE firm_specialization.id_specialization IN ($spec)
AND (SELECT count(id_vacancy) FROM vacancy WHERE id_firm = firms.id_firm) > 0");
          
          
        ob_start();
            echo '<BR>';
            echo '<BR>';
            include BLOCKS.'getListFirmsHere.php';
            $answer['text2']  .= ob_get_contents();
        
        ob_end_clean();
        
        
        if ($vacancyFree == 1)                   
                $query = mysql_query("SELECT DISTINCT firms.id_firm AS id_firm, firms.telephone AS telephone, firms.description AS description, firms.name AS name, building.lat, building.lng FROM firms
                  LEFT JOIN building_offices USING (id_office)
                  LEFT JOIN building USING (id_building)
LEFT JOIN firm_specialization
USING (id_firm)
WHERE firm_specialization.id_specialization IN ($spec)
AND (SELECT count(id_vacancy) FROM vacancy WHERE id_firm = firms.id_firm) >= 0");
        else
            $query = mysql_query("SELECT DISTINCT firms.id_firm AS id_firm, firms.telephone AS telephone, firms.description AS description, firms.name AS name, building.lat, building.lng FROM firms
                  LEFT JOIN building_offices USING (id_office)
                  LEFT JOIN building USING (id_building)
LEFT JOIN firm_specialization
USING (id_firm)
WHERE firm_specialization.id_specialization IN ($spec)
AND (SELECT count(id_vacancy) FROM vacancy WHERE id_firm = firms.id_firm) > 0");


       
            $i = 0;
            $str = '';

            while ($result = mysql_fetch_array($query)){
                $obj['name'] = $result['name'];
                $obj['lat'] = $result['lat'];
                $obj['lng'] = $result['lng'];
                $obj['id'] = $i;
                
                
                
                
                 //проверка на расстояние
                    $lat1rad = pi()*($result['lat'])/180;
                    $lng1rad = pi()*($result['lng'])/180;
                    
                    $k = 117; //коэффициент
                    
                    if ( $lat0rad != 0 && $lng0rad != 0 )
                        $distance = (180/pi())*$k*sqrt(($lat1rad-$lat0rad)*($lat1rad-$lat0rad) + cos($lng0rad)*cos($lng0rad)*(($lat1rad-$lat0rad)*($lat1rad-$lat0rad)));
                    else
                        $distance = 0;
                    
                //echo $distance;
                if ($distance < $way) {
                    $str[$i] = $obj;
                    $i++;
                }
            }
       
       $answer['coord'] = $str;
            
        
        
        //****************************************
        

        
        $answer['lat'] = $lat;
        $answer['lng'] = $lng;
            

        $objJSON = new Service_JSON(); // иницилизация объета JSON
        echo $objJSON->encode($answer);  
              
            
    break;
    
    
    case "getFiltr":
        
        $error = NULL;
        
        $storage = $dataFromClient['storage'];
        
        $latAround = absolutelyEscapeString($storage['map']['centerLat']);
        $lngAround = absolutelyEscapeString($storage['map']['centerLng']);
        $zoom = absolutelyEscapeString($storage['map']['zoom']);
        $city = absolutelyEscapeString($storage['ourGeo']['ourCity']);
        $aim = absolutelyEscapeString($storage['search']['aim']);
        $searchWord = absolutelyEscapeString($storage['search']['searchWord']);
        $freeOffice = absolutelyEscapeString($storage['search']['freeOffice']);
        $freeVacancy = absolutelyEscapeString($storage['search']['freeVacancy']);
        $showSpecForm = absolutelyEscapeString($storage['search']['showSpecForm']);
        $salaryFrom =  absolutelyEscapeString( $storage['search']['salaryFrom'] );
        $experienceFrom =  absolutelyEscapeString( $storage['search']['experienceFrom'] );
        $ageFrom =  absolutelyEscapeString( $storage['search']['ageFrom'] );
        $ageUnder =  absolutelyEscapeString( $storage['search']['ageUnder'] );
        $page = absolutelyEscapeString( $storage['search']['page'] );
        
        
        //*********
            //specialization
            if (isset($storage['search']['specialization']))
                $specialization = $storage['search']['specialization'];
            else
                $specialization = array();

            $specialization_ = array();
            foreach ($specialization as $key => $value)
            array_push( $specialization_, absolutelyEscapeString ($value) );

            unset($specialization);        
                $specialization = $specialization_;
            unset ($specialization_);
        //****
            //specialization_INS!!!
            if (isset($storage['search']['specialization_ins']))
                $specialization_ins = $storage['search']['specialization_ins'];
            else
                $specialization_ins = array();

            $specialization_ins_ = array();
            foreach ($specialization_ins as $key => $value)
            array_push( $specialization_ins_, absolutelyEscapeString ($value) );

            unset($specialization_ins);        
                $specialization_ins = $specialization_ins_;
            unset ($specialization_ins_);
            
        //***
        if (isset($storage['search']['arrPodRazdel']))
            $arrPodRazdel = $storage['search']['arrPodRazdel'];
        else
            $arrPodRazdel = array();
       
        $arrPodRazdel_ = array();
        foreach ($arrPodRazdel as $key => $value)
            $arrPodRazdel_[absolutelyEscapeString ($key)] = absolutelyEscapeString ($value);

        unset($arrPodRazdel);        
            $arrPodRazdel = $arrPodRazdel_;
        unset ($arrPodRazdel_);
        
        if (!filter_var($latAround, FILTER_VALIDATE_FLOAT) && $latAround <= 90 && $latAround >= -90)
                $latAround = NULL;
        
        if (!filter_var($lngAround, FILTER_VALIDATE_FLOAT) && $lngAround <= 180 && $lngAround >= -180)
                $lngAround = NULL;
        
        if (!filter_var($zoom, FILTER_VALIDATE_INT) && $zoom <= 15 && $zoom >= 2)
                $zoom = NULL;
        
        if (!filter_var($aim, FILTER_VALIDATE_INT) && $aim <= 1 && $zoom >= 4)
                $aim = NULL;
        
        if (!is_null($latAround) && !is_null($lngAround) && !is_null($zoom) && !is_null($aim)) {

   
        } else {
                $error = 'Ошибка данных. Обратитесь за справкой к администратору';
        }
            
        if(!$error) {
            
            if ($zoom > 8)
                $radius = (3/8) * pow(2, 15-$zoom);
            else
                $radius = 0;
            
            $difLat = $radius/117;
            $difLng = 5*($radius/117)*cos($lngAround*pi()/180);
            
            //*********************************************
            //считаем количество зданий
            
            $queryBuild = "SELECT name, id_building, lat, lng FROM building 
                WHERE ABS (lat-'$latAround') < '$difLat'
                    AND ABS (lng-'$lngAround') < '$difLng'
LIMIT 0, 1000";          
            
            $queryBuild_ = mysql_query ($queryBuild );
            $numBuild = mysql_num_rows($queryBuild_); 
            
            //***
            //считаем фирмы
            $queryFirms = mysql_query("SELECT firms.name, firms.id_firm, building.lat, building.lng FROM firms 
                                            LEFT JOIN building_offices USING (id_office)
                                            LEFT JOIN building USING (id_building)
                                            WHERE ABS (building.lat-'$latAround') < '$difLat'
                                            AND ABS (building.lng-'$lngAround') < '$difLng'
                                            AND not isnull(building.lat)
                                            LIMIT 0, 1000");          
            
            
            $numFirms = mysql_num_rows($queryFirms); 
            
            //считаем свободные офисы
            $queryOffice = mysql_query("SELECT building_offices.id_office, building.lat, building.lng FROM building_offices
                                            LEFT JOIN firms USING (id_office)
                                            LEFT JOIN building USING (id_building)
                                            WHERE ABS (building.lat-'$latAround') < '$difLat'
                                            AND ABS (building.lng-'$lngAround') < '$difLng'
                                            AND not isnull(firms.name)
                                            LIMIT 0, 1000");          

            
            $numOffice = mysql_num_rows($queryOffice); 
            
            

            $numVacancy = 10;
            $numInsertion = 10;
            
            if ($aim == 1) {
                  $storage['message'] = ''; 
            ob_start();
                include BLOCKS.'filtrSearch/yourCity.php';
                echo '<BR>';
                echo '<BR>';
                include BLOCKS.'filtrSearch/aimSearch.php';
                echo '<BR>';
                include BLOCKS.'filtrSearch/fieldsBC.php';
                
                echo '<BR>';
                include BLOCKS.'filtrSearch/searchWord.php';
                
                $storage['message']  .= ob_get_contents();    
            ob_end_clean();

         
                        $i = 0;
            $str = '';
         

              
            $select = "SELECT building.name AS name, building.id_building AS id_building, building.lat AS lat, building.lng AS lng FROM building 
            WHERE ABS (lat-'$latAround') < '$difLat'
                      AND ABS (lng-'$lngAround') < '$difLng'";
            
            
            $condition1 = " AND building.id_building
IN (
    SELECT id_building
    FROM building_offices
    WHERE id_office NOT
    IN (
        SELECT id_office
        FROM firms
        )
    )";

           $condition2 = "AND building.id_building
IN (
    SELECT id_building
    FROM building_offices
    WHERE id_office NOT
    IN (
        SELECT id_office
        FROM firms WHERE id_firm
            IN(
                SELECT id_firm FROM vacancy
            )
        )
    )" ;
            
           
            if ($freeOffice == 'true') {
                $queryBuild = $select.$condition1;
                
            } else
                $queryBuild = $select;
            
            if ($freeVacancy == 'true') 
                $queryBuild .= $condition2;
                
            
            
            $query = mysql_query ($queryBuild);
            
            $bcString = '';
            
            $beginList = ($page-1)*10;
            $endList = ($page)*10;
            
            while ($result = mysql_fetch_array ( $query) ){
                
               if (  ($searchWord == '') || ( false !== mb_strpos( mb_strtolower($result['name'], 'UTF-8'), mb_strtolower($searchWord, 'UTF-8' ) ) ) ) { 
                
                   
                   
                $str[$i]['name'] = $result['name'];
                $str[$i]['lat'] = $result['lat'];
                $str[$i]['lng'] = $result['lng'];
                $i++;
                
                $nameBuild = $result['name'];
                
                if ($i <= $endList && $i >= $beginList) {
                    ob_start();
                        include BLOCKS.'filtrSearch/bcString.php';
                        $bcString .= ob_get_contents();     
                    ob_end_clean();
                }
                
               }
            }
            

         $storage['message']  .= '<BR>Количество результатов : '.$i.'<BR>';  
         $storage['message']  .= $bcString;  
  
        ob_start();
            include BLOCKS.'filtrSearch/pager.php';
            $storage['message'] .= ob_get_contents();     
        ob_end_clean();
            
            
            $storage['map']['markersOut'] = $str;
            
            } //end if  aim == 1 
            
            //фирмы
             if ($aim == 2) {
                
        
                
                $storage['message'] = ''; 
                
                ob_start();
                include BLOCKS.'filtrSearch/yourCity.php';
                echo '<BR>';
                echo '<BR>';
                include BLOCKS.'filtrSearch/aimSearch.php';
                echo '<BR>';
                include BLOCKS.'filtrSearch/fieldsFirm.php';
                
                echo '<BR>';
                include BLOCKS.'filtrSearch/searchWord.php';
                
                $storage['message']  .= ob_get_contents();    
                ob_end_clean();  

            
            
            //*************************************************
            $i = 0;
            $str = '';
            
            $listIdSpec = '999, ';
           foreach($specialization as $key => $value) {
               $listIdSpec .= $value.', ';
           };
            
           $listIdSpec = substr($listIdSpec, 0, strlen($listIdSpec) - 2);
            
            $select = "SELECT firms.id_firm, firms.name AS name, building.lat AS lat, building.lng AS lng
            FROM firms
            
            LEFT JOIN building_offices USING(id_office)
            LEFT JOIN building USING (id_building) 
            
            WHERE firms.id_office IN (
                SELECT building_offices.id_office
                FROM building_offices
                WHERE building_offices.id_building IN (
                    SELECT building.id_building
                    FROM building 
                    WHERE ABS (lat-'$latAround') < '$difLat'
                    AND ABS (lng-'$lngAround') < '$difLng'
                )
            )
            AND firms.id_firm IN (
                SELECT id_firm
                FROM firm_specialization
                WHERE id_specialization IN ($listIdSpec)
            )
           ";
            
            if ($freeVacancy == 'true') 
           $select .= "AND firms.id_firm IN (
                        SELECT vacancy.id_firm
                        FROM vacancy
                        )
                      ";
            
            
               
          //echo $select;

             $query = mysql_query ($select);
            
             $numFirms = mysql_num_rows($query);
             
            $vacancyString = '';
            
            $str = '';
            $i = 0;
            
            $beginList = ($page-1)*10;
            $endList = ($page)*10;
            
            while ($result = mysql_fetch_array ( $query) ){
                
               if (  ($searchWord == '') || ( false !== mb_strpos( mb_strtolower($result['name'], 'UTF-8'), mb_strtolower($searchWord, 'UTF-8' ) ) ) ) { 
                   
                    $str[$i]['name'] = $result['name'];
                    $str[$i]['lat'] = $result['lat'];
                    $str[$i]['lng'] = $result['lng'];
                    $i++;

                    $nameBuild = $result['name'];
                    
                   if ($i <= $endList && $i >= $beginList) {
                        ob_start();
                            include BLOCKS.'filtrSearch/vacancyString.php';
                            $vacancyString .= ob_get_contents();     
                        ob_end_clean();
                    }
                
               }
            }
            
             $storage['message'] .= $vacancyString;       
             
              ob_start();
                include BLOCKS.'filtrSearch/pager.php';
                $storage['message'] .= ob_get_contents();     
              ob_end_clean();
              
            $storage['map']['markersOut'] = $str;
        }//end if aim == 2
            
            if ($aim == 3) {
                
        
        $salaryFrom =  absolutelyEscapeString( $storage['search']['salaryFrom'] );
        
        if (!filter_var($salaryFrom, FILTER_VALIDATE_INT) || $salaryFrom <= 1) $salaryFrom = 0;
        
        if (!filter_var($experienceFrom, FILTER_VALIDATE_INT) || $experienceFrom <= 1){ $experienceFrom = 0; };
        
        if (!filter_var($ageFrom, FILTER_VALIDATE_INT) || $ageFrom <= 1){ $ageFrom = 0; };
        
        if (!filter_var($ageUnder, FILTER_VALIDATE_INT) || $ageUnder > 50){ $ageUnder = 50; };
        
                
                
                
                $storage['message'] = ''; 
                
                ob_start();
                include BLOCKS.'filtrSearch/yourCity.php';
                echo '<BR>';
                echo '<BR>';
                include BLOCKS.'filtrSearch/aimSearch.php';
                echo '<BR>';
                include BLOCKS.'filtrSearch/fieldsVacancy.php';
                
                echo '<BR>';
                include BLOCKS.'filtrSearch/searchWord.php';
                
                $storage['message']  .= ob_get_contents();    
                ob_end_clean();  

            
            
            //*************************************************
            $i = 0;
            $str = '';
            
            $listIdSpec = '999, ';
           foreach($specialization as $key => $value) {
               $listIdSpec .= $value.', ';
           };
            
           $listIdSpec = substr($listIdSpec, 0, strlen($listIdSpec) - 2);
            
            $select = "SELECT vacancy.id_vacancy, vacancy.name AS name, building.lat AS lat, building.lng AS lng
            FROM vacancy
            
            LEFT JOIN firms USING(id_firm)
            LEFT JOIN building_offices USING(id_office)
            LEFT JOIN building USING (id_building) 
            
            WHERE vacancy.salary_from > '$salaryFrom'
            AND vacancy.experienceFrom > '$experienceFrom'
            AND vacancy.age_from > '$ageFrom'
            AND vacancy.age_under < '$ageUnder'
            AND vacancy.id_firm IN (
                SELECT firms.id_firm
                FROM firms, firm_specialization
                WHERE firms.id_office IN (
                    SELECT building_offices.id_office
                    FROM building_offices
                    WHERE building_offices.id_building IN (
                        SELECT building.id_building
                        FROM building 
                        WHERE ABS (lat-'$latAround') < '$difLat'
                        AND ABS (lng-'$lngAround') < '$difLng'
                    )
                )
                AND vacancy.id_firm IN (
                    SELECT id_firm
                    FROM firm_specialization
                    WHERE id_specialization IN ($listIdSpec)
                )
            )";
            
            
               
          // echo $select;

             $query = mysql_query ($select);
            
            $vacancyString = '';
            
            $str = '';
            $i = 0;
            
            while ($result = mysql_fetch_array ( $query) ){
                
               if (  ($searchWord == '') || ( false !== mb_strpos( mb_strtolower($result['name'], 'UTF-8'), mb_strtolower($searchWord, 'UTF-8' ) ) ) ) { 
                   
                    $str[$i]['name'] = $result['name'];
                    $str[$i]['lat'] = $result['lat'];
                    $str[$i]['lng'] = $result['lng'];
                    $i++;

                    $nameBuild = $result['name'];

                    ob_start();
                        include BLOCKS.'filtrSearch/vacancyString.php';
                        $vacancyString .= ob_get_contents();     
                    ob_end_clean();
                
                
               }
            }
            
             $storage['message'] .= $vacancyString;           
            
            $storage['map']['markersOut'] = $str;
        }//end if aim == 3
        
        if ($aim == 4) {
            
             $salaryFrom =  absolutelyEscapeString( $storage['search']['salaryFrom'] );
        
        if (!filter_var($salaryFrom, FILTER_VALIDATE_INT) || $salaryFrom <= 1) $salaryFrom = 0;
        
        if (!filter_var($experienceFrom, FILTER_VALIDATE_INT) || $experienceFrom <= 1){ $experienceFrom = 0; };
        
        if (!filter_var($ageFrom, FILTER_VALIDATE_INT) || $ageFrom <= 1){ $ageFrom = 0; };
        
        if (!filter_var($ageUnder, FILTER_VALIDATE_INT) || $ageUnder > 50){ $ageUnder = 50; };
        
                
                
                
                $storage['message'] = ''; 
                
                ob_start();
                include BLOCKS.'filtrSearch/yourCity.php';
                echo '<BR>';
                echo '<BR>';
                include BLOCKS.'filtrSearch/aimSearch.php';
                echo '<BR>';
                include BLOCKS.'filtrSearch/fieldsInsertion.php';
                
                echo '<BR>';
                include BLOCKS.'filtrSearch/searchWord.php';
                
                $storage['message']  .= ob_get_contents();    
                ob_end_clean();  

            
            
            //*************************************************
            $i = 0;
            $str = '';
            
            $listIdSpec = '999, ';
           foreach($specialization_ins as $key => $value) {
               $listIdSpec .= $value.', ';
           };
            
           $listIdSpec = substr($listIdSpec, 0, strlen($listIdSpec) - 2);
            
            $select = "SELECT neftemagnat_bulletin_board.id_bulletin_board, neftemagnat_bulletin_board.name AS name, neftemagnat_bulletin_board.lat AS lat, neftemagnat_bulletin_board.lng AS lng
            FROM neftemagnat_bulletin_board
           
            WHERE ABS (lat-'$latAround') < '$difLat'
                   AND ABS (lng-'$lngAround') < '$difLng'
           AND market_type IN ($listIdSpec)";
            
            
               
          //echo $select;

             $query = mysql_query ($select);
            
            $insertionString = '';
            
            $str = '';
            $i = 0;
            
            while ($result = mysql_fetch_array ( $query) ){
                
               if (  ($searchWord == '') || ( false !== mb_strpos( mb_strtolower($result['name'], 'UTF-8'), mb_strtolower($searchWord, 'UTF-8' ) ) ) ) { 
                   
                    $str[$i]['name'] = $result['name'];
                    $str[$i]['lat'] = $result['lat'];
                    $str[$i]['lng'] = $result['lng'];
                    $i++;

                    $nameInsertion = $result['name'];

                    ob_start();
                        include BLOCKS.'filtrSearch/insertionString.php';
                        $insertionString .= ob_get_contents();     
                    ob_end_clean();
                
                
               }
            }
            
             $storage['message'] .= $insertionString;           
            
            $storage['map']['markersOut'] = $str;
            
            
            
            
            
            
        } //end if aim == 4
        
                    $objJSON = new Service_JSON(); // иницилизация объета JSON
                    echo $objJSON->encode($storage); 
            } // end if !error
        
    break;    
    
    case "getCoordCity":
        
        $city = absolutelyEscapeString($dataFromClient['city']);
        
        $cityTranslit = translitIt($city);
        
        $query = mysql_query("SELECT latitude, longitude
                FROM geoip_city
                WHERE city='$cityTranslit'");
        
        
        if ($result = mysql_fetch_array($query) ) {
            
            $answer['lat'] = $result['latitude'];
            $answer['lng'] = $result['longitude'];
            $answer['error'] = FALSE;
        } else {
            $answer['error'] = TRUE;  
        }
        
          $objJSON = new Service_JSON(); // иницилизация
          echo $objJSON->encode($answer);
          
    break;
    
    case "editBuilding":

        /*
        * получение данных от клиента
        */
        $buildInfo = $dataFromClient['info'];

         /*
        * обезопасниваниввание данных, полученных от JS.
        */        
        //$name = iconv('UTF-8', 'windows-1251', $buildInfo['name']);
        $name = absolutelyEscapeString($buildInfo['name']);

       // $telephone = iconv('UTF-8', 'windows-1251', $buildInfo['telephone']);
        $telephone = absolutelyEscapeString($buildInfo['telephone']);

        //$site = iconv('UTF-8', 'windows-1251', $buildInfo['site']);
        $site = absolutelyEscapeString($buildInfo['site']);

        //$typeInn = iconv('UTF-8', 'windows-1251', $buildInfo['typeInn']);
        $typeInn = absolutelyEscapeString($buildInfo['typeInn']);

       // $class_ = iconv('UTF-8', 'windows-1251', $buildInfo['class_']);
        $class_ = absolutelyEscapeString($buildInfo['class_']);

       // $year = iconv('UTF-8', 'windows-1251', $buildInfo['year']);
        $year = absolutelyEscapeString($buildInfo['year']);

       // $numberFloors = iconv('UTF-8', 'windows-1251', $buildInfo['numberFloors']);
        $numberFloors = absolutelyEscapeString($buildInfo['numberFloors']);

       // $lat = iconv('UTF-8', 'windows-1251', $buildInfo['lat']);
        $lat = absolutelyEscapeString($buildInfo['lat']);

        //$lng = iconv('UTF-8', 'windows-1251', $buildInfo['lng']);
        $lng = absolutelyEscapeString($buildInfo['lng']);

        //$latExact = iconv('UTF-8', 'windows-1251', $buildInfo['latExact']);
        $latExact = absolutelyEscapeString($buildInfo['latExact']);

        //$lngExact = iconv('UTF-8', 'windows-1251', $buildInfo['lngExact']);
        $lngExact = absolutelyEscapeString($buildInfo['lngExact']);

        //$addressFull = iconv('UTF-8', 'windows-1251', $buildInfo['addressFull']);
        $addressFull = absolutelyEscapeString($buildInfo['addressFull']);

        //$city = iconv('UTF-8', 'windows-1251', $buildInfo['city']);
        $city = absolutelyEscapeString($buildInfo['city']);

       // $square = iconv('UTF-8', 'windows-1251', $buildInfo['square']);
        $square = absolutelyEscapeString($buildInfo['square']);

        //$address = iconv('UTF-8', 'windows-1251', $buildInfo['address']);
        $address = absolutelyEscapeString($buildInfo['address']);

        //$numStuff = iconv('UTF-8', 'windows-1251', $buildInfo['numStuff']);
        $numStuff = absolutelyEscapeString($buildInfo['numStuff']);
        
        $idBuild = absolutelyEscapeString($buildInfo['idBuild']);

        /*
        * Дальше идет блок, который проверят корректность введенных данных
        */
        $error = NULL;

        //$name
        if ($name == '' && !$error)
            $error = 'Вы не ввели название фирмы';

        if (strlen($name) < 10 && !$error)
            $error = 'Слишком короткое название фирмы';

        if (strlen($name) > 500 && !$error)
            $error = 'Слишком длинное название фирмы';


        //$telephone
        if ($telephone == '' && !$error)
            $error = 'Вы не ввели телефон';

        if (strlen($telephone) < 3 && !$error)
            $error = 'Слишком короткий номер телефона';

        if (strlen($telephone) > 15 && !$error)
            $error = 'Слишком длинное номер телефона';


        //$site
        if (empty($site) && !$error)
            $error = 'Вы не ввели сайт';

        if (strlen($site) < 3 && !$error)
            $error = 'Слишком короткий адрес сайта';

        if (strlen($site) > 35 && !$error)
            $error = 'Слишком длинный адрес сайта';


        //$typeInn   
        if (($typeInn == '' || $typeInn == '0') && !$error)
            $error = 'Вы не выбрали тип здания';

        if (!filter_var($typeInn, FILTER_VALIDATE_INT) && !$error)
            $error = "Неизвестная ошибка_log.1 (что-то с типом здания)";

        if (!$error && ( $typeInn < 0 || $typeInn > 7))
            $error = "Неизвестная ошибка_log.2 (что-то с типом здания)";


        //$class
        if (($class_ == '' || $class_ == '0') && !$error)
            $error = 'Вы не выбрали класс здания';

        if (!filter_var($class_, FILTER_VALIDATE_INT) && !$error)
            $error = "Неизвестная ошибка_log.3 (что-то с классом здания)";

        if (!$error && ( $class_ < 0 || $class_ > 7))
            $error = "Неизвестная ошибка_log.4 (что-то с классом здания)";

        //$year
        if (($year == '' || $year == '0') && !$error)
            $error = 'Вы не выбрали год постойки здания';

        if (!filter_var($year, FILTER_VALIDATE_INT) && !$error)
            $error = "Неизвестная ошибка_log.5 (что-то с годом здания)";

        if (!$error && ( $year < 1800 || $year > 2012))
            $error = "Неизвестная ошибка_log.6 (что-то с годом здания)";

        //$numberFloors
        if (($numberFloors == '' || $numberFloors == '0') && !$error)
            $error = 'Вы не указали количество этажей в здании';

        if (!filter_var($numberFloors, FILTER_VALIDATE_INT) && !$error)
            $error = "Неизвестная ошибка_log.7 (что-то с количество этажей не так)";

        if (!$error && $numberFloors < 0 )
            $error = "Количество этажей не может быть отрицательным";

        if (!$error && $numberFloors > 100)
            $error = "Слишком большое количество этажей";

        //$square
        if (($square == '' || $square == '0') && !$error)
            $error = 'Вы не указали площадь здания';

        if (!filter_var($square, FILTER_VALIDATE_INT) && !$error)
            $error = "Неизвестная ошибка_log.8 (что-то с площадью здания)";

        if (!$error && $square < 0 )
            $error = "Площадь здания не может быть отрицательной";

        if (!$error && $square > 10000000)
            $error = "Слишком большая площадь здания";

        //$idUser
        if (!$idUser && !$error)
            $error = "Неизвестная ошибка_log.9 (что-то с регистрацией пользователя)";


        //$lat
        if ($lat != '' && $lat != '0' && !$error)
            if (!filter_var($lat, FILTER_VALIDATE_FLOAT))
                $error = "Неизвестная ошибка_log.20 (что-то с неточной широтой)";

        //$lng
        if ($lng != '' && $lng != '0' && !$error)
            if (!filter_var($lng, FILTER_VALIDATE_FLOAT))
                $error = "Неизвестная ошибка_log.21 (что-то с неточной долготой)";   


        //$latExact
        if ($latExact != '' && $latExact != '0' && !$error)
            if (!filter_var($latExact, FILTER_VALIDATE_FLOAT))
                $error = "Неизвестная ошибка_log.22 (что-то с точной широтой)";

        //$lngExact
        if ($lngExact != '' && $lngExact != '0' && !$error)
            if (!filter_var($lngExact, FILTER_VALIDATE_FLOAT))
                $error = "Неизвестная ошибка_log.23 (что-то с точной долготой)";  

        if ((strlen($address) == 0 || $address == 'введите адрес') && !$error)
            $error = 'Не указан адрес';

        if (strlen($address) < 10 && !$error)
            $error = 'Адрес слишком короткий';

        if (strlen($address) > 300 && !$error)
            $error = 'Адрес слишком длинный';

        //$numStuff
        if (($numStuff == '' || $numStuff == '0') && !$error)
            $error = 'Вы не указали количество обслуживающего персонала';

        if (!filter_var($numStuff, FILTER_VALIDATE_INT) && !$error)
            $error = "Неизвестная ошибка_log.24 (что-то с полем ОБСЛУЖИВАЮЩИЙ ПЕРСОНАЛ)";

        if (!$error && $numStuff < 0 )
            $error = "Количество персонала не может быть отрицательным";

        if (!$error && $numStuff > 1000)
            $error = "Слишком большое количество обслуживающего персонала";

        //$city
        if (($city == '' || $city == '0') && !$error)
            $error = 'Вы не ввели или неправильно указали город';
        
        
        if (!$error) {
            $query = mysql_query("SELECT city_id
                FROM city
                WHERE name = '$city'");

            if (!mysql_fetch_array($query))
                $error = 'Не существует введенного города';          
        }

        //*******************************************************************
        //конец блока проверки корректности введенных данных
        //*******************************************************************

            $objJSON = new Service_JSON(); // иницилизация объета JSON

            if ($error) {
                // $error = iconv("cp1251", "utf-8", $error);
                $arrMess['status'] = 'false';
                $arrMess['error'] = $error;
                echo $objJSON->encode($arrMess);
            } else {

                /*
                * регистрация
                */
                $lat_ = $lat;
                $lng_ = $lng;

                if ($latExact != '' && $lngExact != ''){
                    $lat_ = $latExact;
                    $lng_ = $lngExact;
                }

                //получение айдишника города
                $query = mysql_query("SELECT city_id
                        FROM city
                        WHERE name = '$city'
                        AND country_id = 3159");

                $result = mysql_fetch_array($query);

                $idCity = $result['city_id'];

                //заносим данные в БД
                mysql_query("UPDATE building SET name = '$name', type = '$typeInn', address = '$address', id_city = '$idCity', phone = '$telephone', site = '$site', class = '$class_', year_building = '$year', floors = '$numberFloors', square = '$square', lat = '$lat_', lng = '$lng_',  staff = '$numStuff'
                        WHERE id_building = '$idBuild'"); 
                        

                //**********************************************************************
                // конец блока регистрации
                //**********************************************************************

                $arrMess['status'] = 'true';
                echo $objJSON->encode($arrMess);
            }
        
        
    break;
    
    case "addOffice":
        
        $numberOffice = absolutelyEscapeString($dataFromClient['numberOffice']);
        $numberFloor = absolutelyEscapeString($dataFromClient['numberFloor']);
        $buildInfo = $dataFromClient['info'];
        $square = absolutelyEscapeString($dataFromClient['square']);
        
        $idBuild = absolutelyEscapeString($buildInfo['idBuild']);
        
        $query = "SELECT id_building
            FROM building_offices
            WHERE number = $numberOffice
            AND id_building = $idBuild";
        
        $query_ = mysql_query($query);
        
        //echo $query;
        if ( $result = mysql_fetch_array($query_) )
           $answer['status'] = FALSE;  
        else {
            
            $query = "INSERT INTO building_offices
                (id_office, id_building, number, square, floor)
                VALUES 
                ('', '$idBuild', '$numberOffice', '$square', '$numberFloor');";        
            
           //echo $query;
            
            mysql_query($query);

        
        
      //  $query = "SELECT id_office, number, floor";
        
        
       ob_start();
            include BLOCKS.'editBuild/addOffice.php';
            $tableOffices .= ob_get_contents();     
       ob_end_clean();
        
       $answer['status'] = TRUE;  
       $answer['message'] = $tableOffices;  
               }
        
          $objJSON = new Service_JSON(); // иницилизация
          echo $objJSON->encode($answer);
       
       
    break;
    
    case "joinToFirm":
        $idFirm = absolutelyEscapeString($dataFromClient['idFirm']);
        $postInFirm = absolutelyEscapeString($dataFromClient['postInFirm']);
        
        if ($idUser) {
            $query = "INSERT INTO firm_participants
                (id_firm, id_participant, start_work)
                VALUES ('$idFirm', '$idUser', '')";
            
            mysql_query($query);
            
           $query = "INSERT INTO firm_post (id_firm, essence_type, id_user, post, start_work)
               VALUES ('$idFirm', '0', '$idUser', '$postInFirm', '')";
            
            mysql_query($query);
        }
        
        
    break;
}
